I have a question about the class, and give the class a specific id.
For example I've got a html code like this:
<div class="test">text1</div>
<div class="test">text2</div>
<div class="test">text3</div>
<div class="test">text4</div>
<div class="test">text5</div>
My question is how can I add an id by each .test class.
I thought something like this in Jquery:
var i = 1;
$('.test').each(function(){
$('.test').attr('id','id_'+i+'');
i++
});
This doesn't work I think it's something with .closest() or .next()
to solve this problem.
Regards,
Frank
EDIT:
I solved the problem by myself the answer is:
$('.test').each(function(){
$(this).attr('class','test').attr('id','id_'+i+'');
i++;
});
No reason to make a counter, .each() comes with one built in.
$('.test').each(function(i){
$(this).attr('id','id_'+i+'');
});
Use $(this) to refer to the current element the in callback function:
var i = 1;
$('.test').each(function(){
$(this).attr('id','id_'+i);
i++
});
Much faster and simpler like this:
$('.test').each(function(i){
this.id = 'id_' + i;
});
There's no need for .attr() when setting or getting the id of an element.
Or if you wanted the numbers to start with 1, do this:
$('.test').each(function(i){
this.id = 'id_' + (i + 1);
});
You were on the right path:
var i = 1;
$('.test').each(function(){
$(this).attr('id','id_'+i+'');
i++
});
Use this jQuery instead:
var i, $test = $('.test'), tl = $test.length;
for (i = 0; i < tl; i++) {
$test.eq(i).attr('id','id_'+i+'');
}
As i is incremented in the for loop, you select the specific element you want to give the i based id with .eq(i).
Related
I wish to do the following but am unsure on how to properly utilize the content targeted within .startsWith.
This is what I have:
var divClass = document.querySelector('div').getAttribute('class');
if (divClass.startsWith('example')){
divClass.classList.add('width', 'height');
}
as shown above, I have attempted to use classList.add() on divClass with no prevail. I believe this strategy is indeed incorrect, however, I believe something like the following is closer...
var divClass = document.querySelector('div').getAttribute('class');
if (divClass.startsWith("example")){
example.classList.add('width', 'height');
}
...Although I struggle to directly target example and use .classList.add() to apply classes to all divs with the example class.
If anyone has a solution to this It'd be greatly appreciated and I thank you in advance!
FYI - All solutions please be in Vanilla JavaScript (No jQuery)
You can use this selector getElementsByClassName
var list = document.getElementsByClassName("example");
for(var i=0;i<list.length;i++){
list[i].classList.add("mystyle");
}
for searching similar classes this solution works
var x = document.querySelectorAll('div');
var i;
for (i = 0; i < x.length; i++) {
if(x[i].classList.value.indexOf('example') > -1){
x[i].classList.add("mystyle");
}
}
Retrieve all the div with the classname starting with example and iterate over the node collection you've found
let divClass = document.querySelectorAll('div[class^="example"]');
[].forEach.call(divClass, function(div) {
/* do something on div */
});
querySelector only gets one element, so you are only selecting the first div on the page and working with that. To get a list of elements, use querySelectorAll.
In jQuery you're able to call $('div').addClass('example') and you don't have to care whether there is one div or a lot, because jQuery handles looping through all of them for you. Without jQuery you have to do the iteration yourself:
var divs = document.querySelectorAll('div');
for ( var i = 0; i < divs.length; i++ ) {
divs[ i ].classList.add('example')
}
Or
document.querySelectorAll('div').forEach(div => div.classList.add('example'))
document.querySelectorAll( selector ) is very similar to $( selector ), but document.querySelector( selector ) is more like $( selector ).first().
I have this code
var $els = document.querySelectorAll('#site-nav a');
for(i = 0; i < $els.length; i++) {
$els[i].addEventListener('mouseover', function() {
console.log('yessss');
});
}
when hovering the element with the mouse I can see the message in the console, but the first time only. Am I doing anything wrong?
thanks
This code seems to work as written: try running the code below.
If you offer a little bit more context we might be able to help more effectively. That being said, it may be worth noting that the mouseover event fires when the mouse enters the element, and doesn't fire constantly while it's over the element.
var $els = document.querySelectorAll('#site-nav a');
for(i = 0; i < $els.length; i++) {
$els[i].addEventListener('mouseover', function() {
console.log('yessss');
});
}
<div id="site-nav"><a>Some link</a></div>
You can achieve what you are looking for by using the .each() function to traverse through all the a elements with id site-nav. I believe it puts all elements into an array for you.
$('#site-nav a').each(function({
\code goes here,you can use $(this) to reference the current a element.
}));
Also watch out when using an id as a selector. Id's are meant for one time use and are meant to be specific to one dom element. Don't know the explanation but iv'e tried to achieve what you are doing using ID's and it does not work.
The code you have works as expected:
If you look at the image you'll see only one line but a number in front of it, that number will increase each time you hover over the link:
var $els = document.querySelectorAll('#site-nav a');
for(i = 0; i < $els.length; i++) {
$els[i].addEventListener('mouseover', function() {
console.log('yessss');
});
}
Fiddle:
https://jsfiddle.net/kkwc3mLn/
Since you're using jQuery that could be simply :
$('body').on('mouseover', '#site-nav a', function(){
console.log('yessss');
});
Hope this helps.
$('body').on('mouseover', '#site-nav a', function(){
console.log('yessss');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="site-nav">
Link1
Link2
Link3
</div>
I need to pass (using javascript) text inside span to href
<div class='tableCell'><span>information</span></div>
<div class='tableCell'><span>contact</span></div>
<div class='tableCell'><span>about</span></div>
for example when i click to about link must be example.com/tag/about/
Here is my Answer. I'm using Javascript to manipulate the DOM to add a new element with the href equal to the inner text within the span element.
I hope you find this answer helpful.
Thanks.
var spans = document.getElementsByTagName('span')
var baseUrl = 'http://example.com/tag/'
for(var i=0; i<spans.length; i++)
{
var curElement = spans[i];
var parent = curElement.parentElement;
var newAElement = document.createElement('a');
var path = baseUrl+curElement.innerHTML;
newAElement.setAttribute('href', path);
newAElement.appendChild(curElement);
parent.appendChild(newAElement)
}
DEMO
The simplest way:
$( "span" ).click(function() {
var link = 'http://yousite.com/tag/'+ $(this).text().replace(/ /, "-")+"/";
window.location.href= link.toLowerCase();
});
DEMO
http://codepen.io/tuga/pen/yNyYPM
$(".tableCell span").click(function() {
var link = $(this).text(), // will provide "about"
href = "http://example.com/tag/"+link; // append to source url
window.location.href=href; // navigate to the page
});
You can try the above code
You do not have links but span in your html. However, you can get build the href you want and assign it to an existing link:
$('div.tableCell').click(function(){
var href = 'example.com/tag/' + $(this).find('span').text();
})
Lets work with pure javascript, I know you want to use jQuery but I am really sure too many people can't do this without looking in to web with pure javascript. So here is a good way.
You can follow it from jsFiddle
var objectList = document.getElementsByClassName("tableCell");
for(var x = 0; x < objectList.length; x++){
objectList[x].addEventListener('click', function(){
top.location.href = "example.com/tag/" + this.childNodes[0].innerHTML;
});
}
Lets work on the code,
var objectList = document.getElementsByClassName("tableCell");
now we have all element with the class tableCell. This is better than $(".tableCell") in too many cases.
Now objectList[x].addEventListener('click', function(){}); using this method we added events to each object.
top.location.href = "example.com/tag/" + this.childNodes[0].innerHTML; with this line if somebody clicks to our element with class: We will change the link to his first child node's text.
I hope it is useful, try to work with pure js if you want to improve your self.
Your Method
If you always are going to have the url start with something you can do something like this. The way it is set up is...
prefix + THE SPANS TEXT + suffix
spaces in THE SPANS TEXT will be converted to -
var prefix = 'http://example.com/tag/',
suffix = '/';
$('span').click(function () {
window.location.href = prefix + $(this).text().replace(' ', '-').trim().toLowerCase() + suffix;
//An example is: "http://example.com/tag/about-us/"
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='tableCell'><span>Information</span></div>
<div class='tableCell'><span>Contact</span></div>
<div class='tableCell'><span>About</span></div>
You can adjust this easily so if you want it to end in .html instead of /, you can change the suffix. This method will also allow you to make the spans have capitalized words and spaces.
JSBIN
Here is what I am trying (jquery):
var lis = $('.options.high');
for (var i = 0; i<lis.length; i++){
console.log(lis[i].html());
}
but this is not allowed I believe. Please suggest some alternative.
Update: Resolved. It was quite silly question. Please ignore.
.html() is method for jQuery objects. Wrap lis[i] like this
$(lis[i]).html()
JS :
var lis = $('.options.high');
for (var i = 0; i<lis.length; i++){
console.log($(lis[i]).html());
}
Demo
A preferable way is to use .each().
var lis = $('.options.high');
lis.each(function(index){
console.log($(this).html()); //OR $(lis[index]).html()
});
Demo
You can use .each() in jquery for this
$('options.high').each(function () {
alert($(this).html());
});
Note: Remove the . before options, if it is not the class name.
I have a feeling this is pretty simple, but my JS is not very good.
I have a div class
<div class=" foo1 foo2" style="top: 0px;">
I can see in chrome that it this div has an attribute set like this:
.foo2
{
position: fixed;
width: 100%;
}
I'm trying to use JS to adjust the attributes of foo2, but I don't know how to get at it.
var changeFoo = document.getElementById ('foo2');
changeFoo.position = "relative";
How do I call foo2.position and change it?
Try this:
Its a pure javascript solution.
function update_this_css(matchClass) {
var elems = document.getElementsByTagName('*'), i;
for (i in elems) {
if((' ' + elems[i].className + ' ').indexOf(' ' + matchClass + ' ')
> -1) {
elems[i].style.position = "relative";
}
}
}
update_this_css('foo2');
You can do it as:
var foo= document.getElementsByClassName('foo2');
for(var i=0;i<foo.length;i++){
foo[i].style.position='relative';
}
You are trying to get the JS to identify an element using its ID ('foo2') which you have not set. If you want to use a class name instead you must use:
document.getElementsByClassName
else you must give your element your desired ID.
Another problem is that you simply have:
changeFoo.position
where as you need to use:
changeFoo.style.position
To get your code to work, you need to loop through the results:
var divs = document.getElementsByClassName('foo');
for(var i=0; i<divs.length; i++) {
divs[i].style.position='fixed'
}
The easiest way I found so far is to use jQuery because regular javascript is so much longer and harder to write. Get a JS library one at jquery.com Learn jQuery once and say thanks to yourself forever :) You can use CSS selectors to get elements without any IDs.
Then use it like this.
$('.foo2').css('position', 'relative');
http://api.jquery.com/css/