Hey guys quick question,
How do you append to a specific div with a specified attribute?
ex.
<div attribute="234"></div>
$('#divwithattribute234').append('test');
Hey guys quick question,
How do you append to a specific div with a specified attribute?
ex.
<div attribute="234"></div>
$('#divwithattribute234').append('test');
This is how you will match your div (<div attribute="234"></div>
):
$("div[attribute=234]").html('Lets write something...');
I strongly recommend reading this post about using custom attributes because that wouldn't be valid even in HTML5 which will allow custom attributes. Why not simply use a class since you can have as many as you want ?
<div class"some_class some_other_class target_class"></div>
Of all the above classes, assuming 'target_class' is the one used for identifying the <div>
, you would select it and append to it with
$(".target_class").html('test');
Update:
If you have more than one target <div>
s and you're looking for a specific one, use a wildcard selector on the trigger (in our case we'll use the ^=
operator which means 'starts with') and then assign its ID to a variable which we then pass to the <div>
selector. Say you want to add your text to a div
when a link is clicked ...
HTML
<a href="#" class="some_class" id="target_div_1">Add to DIV 1</a><br />
<a href="#" class="some_class" id="target_div_2">Add to DIV 2</a><br />
<a href="#" class="some_class" id="target_div_3">Add to DIV 3</a><br />
<div class="some_other_class target_1">Div 1</div>
<div class="some_other_class target_1">Div 2</div>
<div class="some_other_class target_1">Div 3</div>
jQuery
$("a[id^=target_div_]").click(function(event) {
var targetID = $(this).attr('id').substr(11);
$("div.target_" + targetID).html('content got inserted in div ' + targetID);
event.preventDefault();
});
See it on JSFiddle.
Hope this helps !