Radical_Activity
Radical_Activity

Reputation: 2738

How to modify HTML attributes inside a variable that contains HTML?

I have a variable that contains some HTML elements & content:

var data = '<h1>This is a demo element. <span>This is a span.</span></h1><div id="div-element" data-id="1">This is a div.</div>';

What I'd like to do is modify the data-id within the #div-element.

What I've tried so far:

console.log($(data).find('#div-element').attr('data-id'));

This returns undefinied.

data = $.parseHTML(data);
console.log($(data).find('#div-element').attr('data-id'));

Tried to parse the HTML also, but it returns undefinied as well.

What am I missing here?

I'm using jQuery but a Javascript solution is just as good.

Upvotes: 0

Views: 279

Answers (3)

Rory McCrossan
Rory McCrossan

Reputation: 337560

The issue is because you're using find() yet there is no root element in the HTML string you're specifying; all the elements are siblings. In this case you can use filter():

var data = '<h1>This is a demo element. <span>This is a span.</span></h1><div id="div-element" data-id="1">This is a div.</div>';

var id = $(data).filter('#div-element').data('id');
console.log(id);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

Also note the use of data('id') over attr('data-id').

Upvotes: 4

gurvinder372
gurvinder372

Reputation: 68383

Create a dummy element div and set data as its innerHTML

var html = `<h1>This is a demo element. <span>This is a span.</span></h1><div id="div-element" data-id="1">This is a div.</div>`;

var div = document.createElement( "div" );
div.innerHTML = html; //set the html string

//change the attribute of the id-Element
div.querySelector( "[id='div-element']" ).setAttribute( "data-id", "2" );
console.log( div.innerHTML );

Upvotes: 0

Tanmay
Tanmay

Reputation: 1165

In this case following will work.

$("<div>" + data + "</div>").find('#div-element').attr('data-id')

Upvotes: -1

Related Questions