WilliamK
WilliamK

Reputation: 1

Replace text inside html tag (not between) using JavaScript

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.

Upvotes: 1

Views: 237

Answers (5)

RobG
RobG

Reputation: 147363

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.

Upvotes: 0

Pedro Borges
Pedro Borges

Reputation: 41

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

Upvotes: 3

Mihai P.
Mihai P.

Reputation: 9357

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'));

Upvotes: 1

Andrew Hubbs
Andrew Hubbs

Reputation: 9426

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

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

Upvotes: 1

VisioN
VisioN

Reputation: 145368

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

document.getElementsByTagName("html")[0].setAttribute("id", "something");

Upvotes: 4

Related Questions