How to get all html elements with a fixed starting string - javascript

I have many html elements with id
like
"demo1"
"demo2"
"demo3"
and many more
"demoNth"
how to get all the elemnts using jquery?

You can use the following :
this will get all elements starting with demo
$("[id^=demo]")
Selector documentation here
Iterate over them using each() ->
$("[id^=demo]").each(function(index) {
alert(index + ': ' + $(this).text());
});
each documentation here

How about
$("[id^=demo]")
Or best way is to use classes

I would suggest giving them a class is the best way.
e.g.
<div id="1" class"group">1</div>
<div id="2" class"group">2</div>
<div id="3" class"group">3</div>
<div id="4" class"group">4</div>
You can then select all these divs using
$(".group")

$("element[id^='demo']") where element is your element type.

jQuery has a selector syntax ([attrname^=prefix]) specifically for matching string prefixes.
For a more general purpose solution which will match the ID against an arbitrary regular expression, you should select all elements that might match, and then .filter() out the ones you actually want, e.g.:
$('div').filter(function() {
return /^demo\d+/.test(this.id);
});

Related

Check is style attribute does not exists using javascript selector method

I'm trying to only select ARTICLE items that do not have the style attribute set.
I could do this easily with jQuery but I'm using a library that is javascript only, called scrollreveal.
I can easy get items that have the style attribute using this ARTICLE[style].
But I want to reverse this and get items that do not have a style attribute, in the same way using a not equal to != operator on the selector.
I've tried this...
// scroll reveal article
window.sr = new ScrollReveal({ reset: false });
sr.reveal('ARTICLE[!=style]', {
duration: 1000
});
But it's not working as expected, does anyone know if its possible to achieve this using not equal too on a attribute selector?
Thanks in advance for any help on this.
Almost there. The :not pseudoclass should do the trick:
article:not([style])
Just use :not([style]):
const matches = document.querySelectorAll('div:not([style])')
console.log(matches)
<div id="foo" style="width:100px;"></div>
<div id="bar"></div>
<div id="baz"></div>
That is if I'm correct in assuming that sr.reveal uses document.querySelector internally.

JQuery: Find all ids starting with any one of the specified Strings

I understand that I can use below selector to select a div starting with one string.
$('[id^="content_"]')
Find All Ids starting with a String
I have Divs that starts with Strings "content_" or "list_".
How do I select all divs on my document that starts with one of above 2 strings?
Something like below that should work,
$('[id^="content_"] OR [id^="content_"]')
You can use comma separated list of jquery selectors
$('[id^="content_"],[id^="list_"]')
Use comma to have multiple selectors. It will consider both
$('[id^=content_],[id^=list_]').each(function(){
alert($(this).text());
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="anchor">Shoaib</div>
<div id="content_anchor">Sajeed</div>
<div id="list_anchor">Chikate</div>

Im forcing to use getElementsByClassName()[] rather than getElementByClass()

I have 8 divs with id="div1","div2","div3".... and a class=divs. I also have a button with class="div1","div2","div3"......
When I click the button with id="div1", it will first remove all the class="selected" to all div that has a class="divs" then only the div with id="div1" will have the class selected. And so on.....
I want to use document.getElementByClass() for removing class but it don't work in my FIDDLE. :(
Instead, Im forced to use document.getElementsByClassName()[]. But it seems so hard to code since it requires me to put the specific arrays for the classname.
This is exactly I want to achieve FIDDLE
There is no getElementByClass for a reason: unlike id, class is not specified to be unique in a document. Which element would you get? No, you need the ability to get all of them. And if you get an array, that's solved by looping, not by repeating rows for each index:
However, your design is inefficient; and if you're already using jQuery, you can write it very tightly. This would be better:
<button class="divbuttons" data-div="div1">div1</button>
<button class="divbuttons" data-div="div2">div2</button>
...
then you can:
$(document).ready(function(){
$('.divbuttons').click(function() {
var div = $(this).data("div");
$('.divs.selected').removeClass('selected');
$('#' + div).addClass('selected');
});
});
This is an easy one. There is no document.getElementByClass
You have document.getElementById or document.getElementByClassName
There's no such thing as getElementByClass() because multiple elements can have the same class. There's getElementById() (elements have unique ids, or at least they're supposed to) and getElementsByClassName(), which returns an array of all elements that match the class specified.
try
$(document).ready(function () {
$("button[class^=div]").click(function () {
$(".divs.selected").removeClass("selected");
$("#" + $(this).attr("class")).addClass("selected");
});
});
DEMO

Selecting a .class inside an .id - javascript

So I am the newest person to javascript and I have an .class inside a couple of Div.id's and am unable to access the id successfully with my .css formatting. Here is my structure.
<div id="mainColumn">
<div id="SpotlightContainer">
<div id="SpotlightText">
<div class="Title"></div>
</div>
</div>
</div>
here is how I try to acces it in JQuery,
$('div.mainColumn div.SpotlightContainer div.SpotlightText div.Title').html(data[0].title);
I can see the data[0].title coming through in Chrome, so I know that isn't the issue.
Can someone please point out where I am going wrong. Thanks.
An id selector starts with a # not a . (which is for a class selector).
You're prefixing IDs with ., but that's for classes. IDs are prefixed with #. You could also use a simpler selector:
$('#mainColumn .Title')
CSS selector for id is #. Your query should be '#mainColumn #SpotlightContainer #SpotlightText div.Title'
Will work ('#' is an id selector. '.' is a class selector!):
$('div#mainColumn div#SpotlightContainer div#SpotlightText div.Title')
However, that selector string will work through any number of children in the hiearchy, independently of how many layers down the child was found. To be more strongly typed, you could specify that the child must be the first child:
$('div#mainColumn > div#SpotlightContainer > div#SpotlightText > div.Title')
..or keep using the whitespace and do not depend on the structure inbetween your elements:
$('div#mainColumn div.Title')
Try this:
$('#mainColumn #SpotlightContainer #SpotlightText .Title');
"#" is used to select id and "." is used to select class.

Is it possible to get a selector using indexOf

Like
<div id="box_1">
<div id="box_2">
<div id="box_3">
If i want to get all id's starting with 'box_' how can i do it something like this..
$("#box_" + anything )
Unfortunately wrapping the div's won't work because it will get all the other divs in side and between the box divs.
I guess i can give them all another class and reference it like that, but just wondering if there's something like this out there.. thanks.
You can use an Attribute Starts With selector:
$("div[id^=box_]");
It is possible with the attribute starts with selector as others have mentioned, but it might be better to give each element a class:
<div id="box_1" class="box"></div>
<div id="box_2" class="box"></div>
<div id="box_3" class="box"></div>
Select with:
$(".box")
Yep:
$('div[id^="box_"]');
In this case, because you are trying to use the ID selector, its better to switch to an element selector, combined with an attribute selector.
You can use an attribute selector:
$('[id^="box_"')
That will give you all elements whose id starts with "box_". If you need to, qualify it with an element:
$('div[id^="box_"')
If you dont know whether it starts or endswith any string then you can try *= selector which will look within the attribute value.
$("div[id*='box_']");

Categories

Resources