1

I see a lot of reference for replacing text between tags or replacing tags identified with an ID, but my task is quite different in that I need to replace part of the tag itself. For example, I want to change...

<body etc>

So that it becomes...

<body somestring etc>

The change needs to be performed in the browser using JavaScript, ie: after a CMS (like Wordpress) has finished with it.

2
  • 1
    You are looking to change attributes in HTML. Commented Dec 6, 2012 at 0:21
  • Nothing yet because I just realised that my question seems to be about setting an attribute like id=xyz when what I really need is the freedom to inject a string that might call a JS function. Commented Dec 6, 2012 at 0:52

5 Answers 5

4

Looks like you need to add new attribute to DOM element:

document.getElementsByTagName("html")[0].setAttribute("id", "something");
Sign up to request clarification or add additional context in comments.

Comments

3

document['getElementsByTagName']('html')[0]['setAttribute']('attr', 'value');

1 Comment

What's the advantage of adding []? Also, how can I use this to add multiple attributes?
1

If you are using jQuery you can accomplish this with a line like the following:

$("html").attr({foo:"bar", baz:"bing"});

Comments

1

If you run a wordpress website you might already be using jquery. With JQuery this is something easy

$('html').attr('id', 'bob');
//just for testing
alert($('html').attr('id'));

3 Comments

This looks like it might work inserting an ID, but what if it was applied to another tag, for example the BODY tag to insert an onLoad statement like: <body onLoad="someFunction();">
If you are using Jquery then you can simply ` $(document).ready(function() { //whatever you want }); ` you can also tie things to on click ` $("#other").click(function() { alert('hellooo'); }); `
You can find more info about what attributes you can change and how here link or about events here link
0

If you are setting the value of standard attributes, just use DOM properties:

document.getElementsByTagName("html")[0].id = 'foo';

or more simply:

document.documentElement.id = 'foo';

It's not a good idea to set non–standard attributes or properties, use data-* attributes instead.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.