This question already has answers here:
jQuery selector regular expressions
(10 answers)
Closed 4 years ago.
I want to get all elements that class contains a number, how can I do that?
I haven't tried anything because I don't really know how to think about it.
This might be related to this question: jQuery selector regular expressions
Using the regex functionality from this page, you should be able to do something like this:
$(':regex(class,.*[0-9].*)');
This can be done by iterating over all desired elements, keeping only those where the className attribute matches a given regex.
var divs = $('div');
var regex = /\d/;
var result = divs.filter(index => regex.test(divs[index].className));
result.each(index => console.log(result[index]));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="x1" class="a"></div>
<div id="x2" class="a1"></div>
<div id="x3" class="2a"></div>
<div id="x4" class="3"></div>
<div id="x5" class="bc"></div>
<div id="x6" class="x4y5z"></div>
Related
This question already has answers here:
Is it possible to append to innerHTML without destroying descendants' event listeners?
(13 answers)
Closed 4 months ago.
Basically, I want to be able to add this code to the end of a parent div:
<br>
<div class="newPlayer">
<h3>Player ${playerCount}</h3>
<hr>
<p>Name:</p>
<input type="text" id="player${playerCount}"></input>
</div>
Here's what I'm currently using:
function newPlayer(){
playerCount++;
document.getElementById("players").innerHTML = document.getElementById("players").innerHTML + `<br><div class="newPlayer">
<h3>Player ${playerCount}</h3>
<hr>
<p>Name:</p>
<input type="text" id="player${playerCount}"></input>
</div>`
}
Which works, but it refreshes all the inputs which is annoying. Any better methods?
It might look something like this. Taking the createElement and Appendchild solutions.
function newPlayer(){
playerCount++;
document.getElementById("players").appendChild(document.createElement(`
<br>
<div class="newPlayer">
<h3>Player ${playerCount}</h3>
<hr>
<p>Name:</p>
<input type="text" id="player${playerCount}"></input>
</div>
`);
}
Of course! Check Element.appendChild
Node.appendChild()
The Node.appendChild() method adds a node to the end of the list of children of a specified parent node. If the given child is a reference to an existing node in the document, appendChild() moves it from its current position to the new position (there is no requirement to remove the node from its parent node before appending it to some other node).
Newer API available!
The Element.append() method supports multiple arguments and appending strings.
Syntax
element.appendChild(aChild)
This question already has answers here:
What do querySelectorAll and getElementsBy* methods return?
(12 answers)
Closed 1 year ago.
I want to add a class with input tags Because there is a problem with my display (it not beautiful) And I have to Add this class by using javascript and my code is as follows But it doesn't work I'm not sure where I went wrong.
mychoices.html
<script>
document.addEventListener('DOMContentLoaded', function() {
new Choices('#choices-remove-button', {
removeItemButton: true,
});
var inputs = document.querySelectorAll('input[type=text]');
inputs.classList.addClass("browser-default");
});
</script>
myform.html
<div class="section">
<form action='.' method='POST'>
{% csrf_token %} {{ form.media }}
{{ form }}
<input type='submit' value='Save' class="button" />
</form>
</div>
Which I added classes browser-default and other existing classes must work correctly.
What should I do?
Thanks
So you're really close.
The first thing to note is that document.querySelectorAll returns a NodeList (like an array of elements). So you'll need to use forEach to loop over each input.
From MDN
The Document method querySelectorAll() returns a static (not live) NodeList representing a list of the document's elements that match the specified group of selectors.
The second thing is that the classList.addClass doesn't exist. It's just classList.add. For more about Element.classList, please refer to this MDN article: https://developer.mozilla.org/en-US/docs/Web/API/Element/classList
Try the following instead:
<script>
document.addEventListener('DOMContentLoaded', function() {
new Choices('#choices-remove-button', {
removeItemButton: true,
});
var inputs = document.querySelectorAll('input[type=text]');
inputs.forEach(function (input) {
input.classList.add("browser-default");
})
});
</script>
X/Y problem "there is a problem with my display" - explain the problem instead of trying to fix a solution that might not be efficient or good practice. Also what is Choices ?
To answer your immediate question:
You are trying to add a class to a node list. That is jQuery syntax.
In vanilla JS, you need to use classList.add to each
document.querySelectorAll('input[type=text]').forEach(input => ;
input.classList.add("browser-default"));
or similar loop
This question already has answers here:
Need to escape a special character in a jQuery selector string
(7 answers)
Closed 4 years ago.
I'm trying to select an element this way
$('#QR~QID345')
because the element's id is QR~QID345 but the selector doesn't work with ~, is there any fix?
Changing the id is not an option in this case.
You can escape ~ with \\
alert( $('#QR\\~QID345').text() );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="QR~QID345">Hello</div>
You can use $.escapeSelector to escapes any character that has a special meaning in a CSS selector.
var id = $.escapeSelector("QR~QID345");
console.log($('#' + id).text());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p id="QR~QID345">
Hello World
</p>
As been noted by Rory McCrossan on the comment, $.escapeSelector was added on version 3.0
Doc: $.escapeSelector()
As you can see, my HTML contains multiple references to '0'. I need to change these to '1'.
However, my jQuery isn't working.
jQuery(".create-new-location").click(function() {
jQuery("#header-logo").html().replace(/\[0\]/g, '['+(1)+']');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="header-logo" class="header-title location-header-0 title-edit-header" data-row-id="location-header-0" title="Location name (for your reference)">
<div class="input-selection title-edit-header">
<div class="text-input">
<input class="option_textbox col-sm-12 change-width title-edit" placeholder="Location name (for your reference)" value="" type="text" name="bp_theme_options[social][map][locations][0][location_name]">
</div>
</div>
<div class="open-block pencil-edit" data-row-id="location-header-0"></div>
</div>
You have to set the html like this
jQuery(".create-new-location").click(function() {
var the_html = jQuery("#header-logo").html().replace(/\[0\]/g, '['+(1)+']');
jQuery("#header-logo").html(the_html);
});
But this is not a good practice!!
When you need to change only the attribute of an <input>, why change the whole #header-logo, right? When you re-draw html like this, you risk losing event-handlers binded to the elements you have just re-drawn.
jQuery(".create-new-location").click(function() {
var elements = jQuery("#header-logo").find('input[name]'); /*all input with name*/
elements.each(function(el){
var the_name = el.attr('name').replace(/\[0\]/g, '['+(1)+']');
el.attr('name', the_name);
});
});
Regexing the html is never a good idea.
As you can see, my HTML contains multiple references to '0'. I need to change these to '1'.
The approach you used, and even the accepted answer here, will not modify the containing div with id="header-logo" which contains several of these references. Moreover, there are significant issues with simply replacing existing dom elements with freshly regexed ones in validation cases (as in, this may break your validation).
The approach you should use is to specifically target the attributes that contain these references, and then only modify those. Here is a general approach which looks in all attributes and modifies the occurrence of [0 (0 being the value of before) into [1 (1 being the value of after) as well as modifying the occurrence of -0 (before = 0) to -1 (after =1).
This will prevent removing any existing event handlers from the elements, as well as a number of other issues associated with regexing straight html and then replacing the dom element with the that result.
$.fn.indexUpdate = function(before,after){
$("*",this).add(this).each(function(){
$(this.attributes).each(function(){
this.value = this.value.replace(new RegExp('\\b\\-'+before+'\\b','g'), '-'+after);
this.value = this.value.replace(new RegExp('\\['+before, 'g'), '['+after);
});
});
};
$("#header-logo").indexUpdate(0,1);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="header-logo" class="header-title location-header-0 title-edit-header" data-row-id="location-header-0" title="Location name (for your reference)">
<div class="input-selection title-edit-header">
<div class="text-input">
<input class="option_textbox col-sm-12 change-width title-edit" placeholder="Location name (for your reference)" value="" type="text" name="bp_theme_options[social][map][locations][0][location_name]">
</div>
</div>
<div class="open-block pencil-edit" data-row-id="location-header-0"></div>
</div>
This statement jQuery("#header-logo").html().replace(/\[0\]/g, '['+(1)+']'); retrieve the html inside the element that have id as header-logo and replace every 0 inside the html string with 1 But it doesn't assign the modified string again to the element So you may want to use following code.
jQuery("#header-logo").html(jQuery("#header-logo").html().replace(/\[0\]/g, '['+(1)+']'));
Try this:It will replace all existence of '0' with '##'
$(".create-new-location").click(function() {
$("#header-logo").html().replace(/0/gi, '##')
});
This question already has answers here:
getElementByClassName Not Returning Results
(2 answers)
Closed 9 years ago.
So, this is the code:
<a id="link" href="https://url.com/">URL:</a>
<input id="value"/>
<script type="text/javascript">
var link= document.getElementById('link');
var input= document.getElementById('value');
input.onchange=input.onkeyup= function() {
link.search= 'extendurl/'+encodeURIComponent(input.value);
};
</script>
this is working, but i need to use the class instead of the ID. I try this:
<script type="text/javascript">
var link= document.getElementByClassName("link")[0];
var input= document.getElementByClassName("value")[0];
input.onchange=input.onkeyup= function() {
link.search= 'extendurl/'+encodeURIComponent(input.value);
link.firstChild.data= link.href;
};
</script>
<a class="link" href="https://url.com/">URL:</a>
<input class="value"/>
i don't know why, but this isn't working.
Someone?
The precise name is important.
Change
getElementByClassName
to
getElementsByClassName
There's a s because there might be more than one element with a give class, contrary to elements with a specific id.
There can be many elements with the exact same class names, so you have to adjust it for that
instead of
getElementByClassName
you have to do
getElementsbyClassName("someclass");
and it will return an array of all of them