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

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.

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

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

In this case following will work.
$("<div>" + data + "</div>").find('#div-element').attr('data-id')

Related

Jquery add data to html before adding to DOM

I am building html on the fly need to add data before I add it to DOM. Since I am looping thru' lot of information, I would like to add the relevant data info along with the dom I am building instead of adding the html and then looping thru again to add the data.
result.forEach(function(record) {
html += '<div id ="' record.ID + '">test content </div> ';
//add data to above
});
I can do another loop here after adding it to DOM
$(body).append(html);
testresult.forEach(function(record) {
$("#" +record.ID).data(record);
});
Instead of concatenating strings to piece together your HTML, you may way to try something like this:
result.forEach(function(record) {
$('.selector').append(function () {
var $div = $('<div></div>');
$div.attr('id', record.testID).text('some text');
return $div;
});
});
This creates a new div jquery object for each item in result. You can use the record object to add attributes, data, text, etc to you object. It will be added the DOM when the callback passed into .append returns your new jquery DOM object.
Start trying to use jQuery to create your html elements so you can take fully advantage of jQuery and its plugins.
Ex:
var div = $("<div></div>") // create the element
.text("test content") // change the inner text
.attr("id", record.testID); // set the element id
div.appendTo("body");
You can check out [http://www.w3schools.com/jquery/] as a great source for learning jQuery.
You have quotes problem in the following line :
html += '<div id =record.testID' + '>test content </div> ';
________^______________________^___^_____________________^
You should fix that using double quotes because as it's now the string will be considered as '<div id =record.testID'.
html += '<div id="'+record.testID+'">test content </div>';
Or you could use separated definition :
$.each(result, function(index,record) {
var div = $('<div>test content</div>');
div.attr('id', record.testID);
div.data('test', record.testDATA);
$('body').append(div);
})
Hope this helps.
var result = [{testID: 1,testDATA: 'data 1'},{testID: 2,testDATA: 'data 2'},{testID: 3,testDATA: 'data 3'}]
var html='';
$.each(result, function(index,record) {
var div = $('<div>test content</div>');
div.attr('id', record.testID);
div.data('test', record.testDATA);
console.log(div.data('test'));
$('body').append(div);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Add new parent div and next a div inside this parent div

I want to do a simple manipulation but i don't understand why it's don't work i have a div :
<input type='button' value='validate' class='popupjq'>
And i want to add a parent div to this input and also a 'brother' div for have this result :
<div id = 'id_parent'>
<input type='button' value='validate' class='popupjq'>
<div id = 'id_brother'></div>
</div>
So i use this javascript :
$(".popupjq").each(function() {
var divParent = $("<div id = 'id_parent' style='display:inline-block; position:relative;'>");
var divCache = $("<div id='toto'>");
$(this).wrap(divParent);
$(divParent).append(divCache);
});//bracket missing
My problem is that the parent div is create but not the brother div.
You can use insertAfter() to put the second element where you require:
$(".popupjq").each(function() {
$(this).wrap('<div id="id_parent" style="display: inline-block; position: relative;"></div>');
$('<div id="toto"></div>').insertAfter(this);
});
Example fiddle
You haven't closed your each-loop properly (check brackets).
You should specify the DIVs' HTML as strings.
Using "each" implies you're
planning to apply this method on several elements. In this case you
should work with classes instead of IDs in your DIVs' HTML, since IDs
are meant to exist exactly one time in the DOM.
You haven't addressed your parent DIV properly (see my approach).
http://jsfiddle.net/1yn8qgg3 (CSS with background colors to visually mark the DIVs)
$(".popupjq").each(function() {
var divParent = "<div class='class_parent'></div>";
var divCache = "<div class='class_toto'></div>";
$(this).wrap(divParent);
$(this).parent().append(divCache);
});
Hope this helps.
Do the following, to get the result
$(function(){
$(".popupjq").each(function() {
var divParent = $("<div id = 'id_parent' style='display:inline-block; position:relative;'> </div>");
var divCache = $("<div id='toto'> </div>");
$(this).wrap(divParent);
$(this).append(divCache);
});
});
Fiddle

Insert HTML after certain paragraph of HTML string

I've got a HTML-string I'd like to render but append some HTML after the 2nd paragraph first.
function insertStuff() {
//var string = "<div><p>paragraph 1</p><p>paragraph 2</p><p>paragraph 3</p></div>"; works
var string = '<p><img src="http://example.com/my-cool-picture.png" alt="alt text"></p><p>2nd paragraph</p><p>3rd paragrpah</p>' // doesn't work
var parsedHtml = $(string)
parsedHtml.find("p:nth-child(2)").after("<p>My cool insert</p>")
return parsedHtml.html()
}
This works for the HTML string above but the following one only return the <img> after invoking parsedHtml.html()
What am I doing wrong?
Since you are use .html() it will return html of first element.
You can wrap your content in a div like
var parsedHtml = $('<div />').html(string)
Then your code will work.
function insertStuff() {
var string = '<p><img src="http://example.com/my-cool-picture.png" alt="alt text"></p><p>2nd paragraph</p><p>3rd paragrpah</p>'
var parsedHtml = $('<div />').html(string)
parsedHtml.find("p:nth-child(2)").after("<p>My cool insert</p>")
return parsedHtml.html()
}
alert(insertStuff())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Try this
function insertStuff() {
var string = '<div><p><img src="http://example.com/my-cool-picture.png" alt="alt text"></p><p>2nd paragraph</p><p>3rd paragrpah</p></div>';
var parsedHtml = $(string)
parsedHtml.find("p:nth-child(2)").after("<p>My cool insert</p>")
return parsedHtml.html()
}
You should put this string in a div as parent.
That's because html method as getter returns html content of the first element in the set. You should either wrap all the top-level elements in the set with another element and read it's html content or iterate through the set and concatenate each element's outerHTML property.
parsedHtml.map(function() { return this.outerHTML; }).get().join('');
If you want to get the innerHTML of all the elements in the set, replace outerHTML with innerHTML.
when you use find() with a selector it will search inside that selector (in child nodes) that why when you use string with div tag you are getting the desired result and when you delete div the problem occured

wrap only text within a selection in jquery

I have the following markup repeating several times on a page:
<div class="RebalanceCellBroadACName">
<img src="someimage.png" />
Accounts
</div>
Where I wish to use jquery to wrap only the word "accounts" in a span with the class .orange-category.
I have found that the following:
$(".RebalanceCellBroadACName").wrapInner("<span class='orange-category' />");
wraps both the image and the text.
This when typed in the console returns all of the instances of the text concatenated together:
$(".RebalanceCellBroadACName").text();
However the following returns an error "undefined is not a function", and I assume this is because I am selecting a string rather than a jQuery object.
$(".RebalanceCellBroadACName").text().wrapAll("<span class='orange-category' />");
So any help would be appreciated as to how to best achieve the folowing result via jquery:
<div class="RebalanceCellBroadACName">
<img src="someimage.png" />
<span class='orange-category' />Accounts</span>
</div>
For every instance of .RebalanceCellBroadACName on the page. Thank you for your help in advance.
A solution :
$(".RebalanceCellBroadACName").each(function(){
var img = $('img', this).detach();
$(this).wrapInner("<span class='orange-category' />").prepend(img);
})
While you don't have access to the text node, you do have access to the children that are DOM elements.
So basically you can clone the parent, remove the children, wrap the text and finally replace it in the original.
$(".RebalanceCellBroadACName").each(function(){
var $this = $(this);
var all_text = $this.html();
var clean_text = $this.clone() //clone the element
.children() //select all the children
.remove() //remove all the children
.end() //again go back to selected element
.text().trim();
var new_text = "<span class='orange-category'>"+clean_text+"</span>"
$this.html(all_text.replace(clean_text, new_text));
})
http://jsfiddle.net/p2he9h2k/

how to get element id of div and appendChild html to it

I want to get the ID of a div using JavaScript that runs inside that div. I want to appendChild() html to that div.
eg:
<div id="randomnumber">
<script type="text/javascript">
var htmlcontent = "abcdf";
//need the id of div holder
var thisDIVid= ?????;
// appendChild to this div
?????.appendChild(htmlcontent);
</script>
</div>
If you know where in the structure your div is placed you can access it like this:
var mainDiv = document.getElementById('mainDiv');
yourDiv = mainDiv.getElementsByTagName('div')[number];
number is the place in the structure
document.getElementyById("yourDivId"); will find any div with an unique ID.
var div = document.getElementyById("yourDivId");
div.appendChild("yourContent");

Categories