How do you append to a specific div with a specified attribute?
ex.
<div attribute="234"></div>
$('#divwithattribute234').append('test');
jQuery('div[attribute=234]').html('test');
Check on jsfiddle
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
Add to DIV 1<br />
Add to DIV 2<br />
Add to DIV 3<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 !
This is how you will match your div (<div attribute="234"></div>):
$("div[attribute=234]").html('Lets write something...');
Related
I know I can select all the HTML elements with a custom attribute by just doing:
$('p[mytag]')
As you can see, I also need to specify the actual HTML div type (a p element in this case). But what if I need to retrieve all the HTML elements irrespective of their type?
Consider this code:
<p>11111111111111</p>
<p mytag="nina">2222222222</p>
<div>33333333333</div>
<div mytag="sara">4444444444</div>
how I can select the 2 html elements (the p and the div) with custom attribute mytag?
You just need to use $("[mytag]")
console.log($("[mytag]"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>11111111111111</p>
<p mytag="nina">2222222222</p>
<div>33333333333</div>
<div mytag="sara">4444444444</div>
Use querySelectorAll (javascript) :
document.querySelectorAll('[mytag]');
Or even simpler with jQuery:
$('[mytag]');
Edit: Thanks for the helpful answers so far! I'm still struggling to print the input to the "right" div, though. What am I missing?
Next to the input field, there is an option to select either "left" or "right". Depending on the selection, the input is to be printed eiether left or right on the click of a button. This is what I have - but it only prints to the left, no matter the selection.
jQuery(document).ready(function(){
$('.button').click(function(){
$('.input').val();
if ($('select').val() == "left"){
$('div.left').html($('.input').val());
}
else {
$('div.right').html($('.input').val());
}
});
});
</script>
Sorry if this is very basic - I am completely new to JS and jQuery.
I'm trying to print input from a form into a div. This is part of the source HTML modify (it's for a university class):
<input type="text" class="input">
<div class="left">
</div>
<div class="right">
</div>
Basically, text is entered into the field, and I need to print this text either to the "left" or the "right" div when a button is clicked.
So far, I have only ever dealt with divs that had IDs, so I used
document.getElementById("divId").innerHTML = ($('.input').val());
But what do I do now when I don't have an ID? Unfortunately, changes to the HTML source are not an option.
Thanks in advance!
Just use normal selectors, like css and jQuery does.
https://api.jquery.com/category/selectors/
in your case:
$('div.left').html($('.input').val());
As you see there are many ways to do this. You can get elements by tag name, class, id...
But the most powerful way is to get it with querySelector
function save() {
var input = document.querySelector('input').value;
document.querySelector('div.left').innerHTML = input;
}
<input type="text" class="input">
<button onclick="save()">Save</button>
<div class="left"></div>
<div class="right"></div>
There are plenty of other ways to target HTML elements, but the one you're looking for in this case is getElementsByTagName(). Note that this returns a NodeList collection of elements, so you'll additionally need to specify the index that you wish to target (starting at 0). For example, if you want to target the second <div> element, you can use document.getElementsByTagName("div")[1].
This can be seen in the following example:
let input = document.getElementsByTagName("input")[0];
let button = document.getElementsByTagName("button")[0];
let div2 = document.getElementsByTagName("div")[1];
button.addEventListener("click", function(){
div2.innerHTML = input.value;
});
<input type="text">
<button>Output</button>
<br /><br />
<div>Output:</div>
<div></div>
Since you have unique class names for each element, document.getElementsByClassName can be used. This will return an array of elements containing the class. Since you only have one element with each class name, the first element of the returned array will be your target.
<input type="text" class="input">
<button onclick="save()">Save</button>
<div class="left"></div>
<div class="right"></div>
<script>
function save() {
var input = document.getElementsByClassName('input')[0].value;
document.getElementsByClassName('left')[0].innerHTML = input;
}
</script>
This is one of the many ways to do what you want:-
Write the following in console:
document.getElementsByTagName("div");
now you can see the total number of div elements used in your current document/page.
You can select one of your choice to work on by using "index number"(as in array index) for that particular div.
Lets say your div having class name = "right" is the 3rd one among the other div elements in your document.
This will be used to access that div element.
document.getElementsByTagName("right")[2].innerHTML = "whatever you want to write";
Is there a way to extract body element without a particular child element in it?
For example, if I have:
<body>
<div id="id1" class="class1" />
<div id="id2" class="class2" />
</body>
, what I need to be extracted is:
<body>
<div id="id1" class="class1" />
</body>
Actually, I intend to use html2canvas library to make canvas element from a HTML code, but I don't want to include all body children in a canvas element.
If you retrieve a parent element then you also have to take all of its children too. A possible workaround in this case would be to select the body, clone it and then remove the unwanted child element, something like this:
var $bodyClone = $('body').clone();
$bodyClone.find('#id2').remove();
// use $bodyClone as needed here...
$('body').not("#id2").html();
or
$('body').not(".class2").html();
and this is for multiple
$( "div" ).not( ".someclass, #someid,.class").html()
hope it will help
you can use document.getElementById(id) to get one element
or getElementsByClassName(class) and then filter the returned array
Using better ids or classes could help you to avoid filtering at all, simply give all your canvases one class and replace them all.
So I have a div that is drawing in dynamic elements at its bottom and I want to hide these elements, no matter what their IDs are using javaScript/jQuery. Basically my HTML looks like this:
<div class="right-panel">
<div class="info">Text</div>
<form id="the-form">
<input type="hidden" name="first-name" value="">
<input type="hidden" name="last-name" value="">
<input type="hidden" name="state" value="">
</form>
<script>javaScript</script>
<div id="dynamic-id-1">Advertisement 1</div>
<div id="dynamic-id-2">Advertisement 2</div>
</div>
I'd like to ensure that the "dynamic-id-1" and "dynamic-id-2" divs are always removed or hidden no matter what their ID's are (their IDs are subject to change). How do I target these elements without targeting their IDs?
Edit--I tried this, but my approach seems limited, and I couldn't get it to work with multiple divs, even when chaining:
$('#the-form').next().hide();
(Note: unfortunately they don't have a class, there are multiple divs, and the IDs are always completely different. I was hoping there might be novel way to target the last two divs of the wrapping div and hide them)
If the script tag is always before the div's that need removing you could do this -
$('.right-panel > script').nextAll('div').remove();
http://jsfiddle.net/w6d8K/1/
Based on what you tried you could do this -
$('#the-form').nextAll('div').hide();
http://jsfiddle.net/w6d8K/2/
Here are the docs for nextAll() - https://api.jquery.com/nextAll/
The simplest route would be to add classes to the dynamic elements. Something like:
<div class="removable-element" id="dynamic-id-1">Advertisement 1</div>
Then, you can do something like:
$(".right-panel .removable-element").remove()
If only one div at a time is generated dynamically. Add this to dynamic generation:
$('#the-form + div').hide();
Another method to achieve the same (not preferred) is:
$('#the-form').next('div').remove();
You are saying you don't want to target their "id", but is there some specific part in the id that will remain the same ?
like for instance "dynamic-id-" ?
If this is the case you can target them by using a "like selector". The code below would target all divs whose ID is starting with "dynamic-id"
$('div[id^=dynamic-id]').each(function () {
//do something here
});
Target the class instead of the dynamic ID.
<div class="element-to-remove" id="dynamic-id-1" />
<div class="element-to-remove" id="dynamic-id-2" />
$('.right-panel . element-to-remove').remove();
I'm struggling a bit with this : let's say I have a class in the body <body class="video page"> and in my page I have a pagination which add a number like this <body class="video-2 page"> at each page. I would like to target the class video whether or not it has a number in order to apply some jquery if the condition is filled.
How do I do that?
You can use this attribute selector to select elements that have a class attribute starting with video-:
[class^="video-"]
But for this to work, you’d have to make sure that the video- class is the first one in the element’s class attribute (see http://jsfiddle.net/Czyep/).
It might be better to have the video class and the pagination class be separate, e.g.:
<body class="video page-2 page">
I would split the classes like class="video two page" so that you can still address both classes separately. Nevertheless you can do something like
$('body[class*=video]')
$("body").not(".video");
Should select all bodies wich end with a number. You could also do:
if($("body").is("[class$='video-'")) {}
have you tried something like this this?
$('.video,.video-'+pageNumber).dosomething()
You can use the attribute starts with selector:
$("body[class^='video']");
Assuming I have understood your question correctly I would suggest that you use concatenation in your selector.
I assume that you are aware that you have specified two classes on your body tag namely video and page or video-2 and page. And I therefore assume that page is significant in your selection and should be included in your selector.
Therefore I would use this syntax whilst not as neat as some syntax it is very clear what is going on. Obviously you would need to incorporate this into what ever logic is driving your page selection.
var suffix = "";
$(".video" + suffix + ".page").dosomething(); // select <body class="video page">
suffix = "-2";
$(".video" + suffix + ".page").dosomething(); // select <body class="video-2 page">
Note that there should be no space between the classes in the selector because they have been declared in the same tag in the html.
Had you specified something like
<body class="video"> // body wrapper
<div class="page"> // page wrapper
</div>
</body>
Then a space would be required as you are then looking to match on div page within body with class video or video-2 as appropriate.
suffix = "-2";
$(".video" + suffix + " .page").dosomething(); // select <body class="video-2"><div class="page">