Get value of text inside span - javascript

I am working with Flexigrid plugin with JQuery. Ok so I have a div with two span elements, they would contain the text/display text for the buttons that flexigrid provides. The problem is, there is no mechanism to add ids to those buttons, except for adding different text.
<div class="tdiv2>
<div class="fbutton">
<div>
<span class="view" style="padding-left: 20px;">Add</span>
</div>
</div>
<div class="fbutton">
<div>
<span class="view" style="padding-left: 20px;">Delete</span>
</div>
</div>
</div>
This is how the buttons are arranged. So onclick of that button, I get the text inside the span, as Add and Delete. Now I want to add a class tag to that span, to differentiate between the active button and the other one.
So I came up with the idea, that if I could get span-text that matches to the text being returned, I could add the class to that span.
But when I do
alert($('.tDiv2 span').html());
I am only getting the text of the first span and not the second one. Could somebody help me with getting the html of both spans and not just the first one.

Try this >
$('.tDiv2 span').each(function(index, el) { alert($(el).html()); });

You need each.
$('.tDiv2 span')each(function(node){ alert(node.html()); });
However, I would like to point out that this approach is likely to cause accessibility problems for screen reader users. If you absolutely must re-invent buttons for some reason, then use ARIA attributes so that your blind visitors have some hope of getting it to work right.

jQuery automatically selects the first element in a series if you try to get a property like html or text from it. to get the second (or any number) try:
alert($('.tDiv2 span').eq(1).html()); //returns 2nd element's html content
You can substitute any 0 based index in for 1.

Related

How can I select all the divs inside a section tag using javascript?

I'm making a turn-based game in javascript. I want to move the player from div to div. I have put all those divs in a section and then into an array using queryselectorall. Now my problem is that I also have another divs who I want to use and I can't select them separately. Can anyone tell me how to select only some divs? I have seen something like section>div to differentiate them, but that doesn't work for me.
I have tried replacing div with span on rollDice, zar1, and zar2, but by doing that some CSS breaks.
~
<div class="rollDice">Roll the dice</div>
<div class="zar1">
<img src="poze/dice-5.png" alt="Dice" class="dice" id="dice-1" style="width:150px">
</div>
<div class="zar2">
<img src="poze/dice-5.png" alt="Dice" class="dice2" id="dice-2" style="width:150px">
</div>
<section class="mutari">
<div class="nr1 mutabil"><h1>1</h1></div>
<div class="nr2 mutabil"><h1>2</h1></div>
<div class="nr3 mutabil"><h1>3</h1></div>
</section>
~
I want to select the div only from the section. And after that I want to select the first 3 divs.
What you are looking for is:
document.querySelectorAll('section > div:nth-child(-n+3)')
section (a type selector) finds your <section>. If you had more section elements, you could use section.mutari to be more precise (using a class selector).
> div selects all the <div> tags that are direct children of that section. > is a child combinator.
:nth-child(-n+3), a pseudo-class, restricts this to only select the first three elements, not all of them. It is not needed in your example, as you only have three divs; but if you had more, this would give you only the first three.
With document.body.childNodes
Just replace document.body with your HTML Element.
You can filter after that through the list you get an select all divs.
If you want to get all divs you can also use following:
var dh = document.body.getElementsByTagName('div');
Get all div nodes:
Use document.body.getElementsByTagName('div')
Or
Get filtered div nodes:
Take array from document.body.childNodes.
filter by using for loop and if condition.
Condition Example: use like node[i].nodeName and node[i].id

Adding and removing classes not working

I've used this exact code on a different div element and it works perfectly. When I went to add the same code to another div element with a different id it registers the element has been clicked but it doesn't add or remove any of the classes.
$('#quoteClick').click(function(){
$('#cbox-1').addClass('displayCboxBackground');
$('#cbox-2').removeClass('displayCboxBackground');
$('#cbox-3').removeClass('displayCboxBackground');
$('#dbox-1').addClass('displayBlock');
$('#dbox-2').removeClass('displayBlock');
$('#dbox-3').removeClass('displayBlock');
console.log("clicked");
});
The html structure is as follows:
<div id="cbox-1">
<div id="dbox-1">
content...
</div>
</div>
<div id="cbox-2">
<div id="dbox-2">
content...
</div>
</div>
<div id="cbox-3">
<div id="dbox-3">
<div id="quoteClick">
a quote
</div>
</div>
</div>
JSFiddle: https://jsfiddle.net/m81c23cx/1/
In the fiddle you can see the content will changes when each header is clicked. When the "quoteClick" element is clicked I want it to change to the second headers content exactly how it does when the second header is clicked.
I can see in Chrome's console that when I click the div element that it highlights all the classes but it doesn't change any of them. I have the jQuery inside a document.ready() function so it should be waiting for the DOM to load and it works perfectly when I just write the lines into the console.
I'm surprised that nobody actually questioned your use of ids (instead of suggesting that you should double-check for dupes). The reason why this code is hard to debug is because it's too complicated. As a result, you'll have a hard time fixing issues similar to this in the future too.
Drop it, do it better.
I didn't even go through your fiddle. Instead, I'm going to propose that you change your approach altogether.
Update your HTML and use classes instead of ids. Something similar to this:
<div class="cbox">
<div class="dbox">
content...
</div>
</div>
<div class="cbox">
<div class="dbox">
content...
</div>
</div>
<div class="cbox">
<div class="dbox">
<div id="quoteAdvert">
a quote
</div>
</div>
</div>
Update your JavaScript and use this to get the context of the current box:
$('.cbox').click( function cboxClicked () {
// Remove the previous class from all .cbox & .dbox elements; we don't care which
$('.cbox').removeClass('displayCboxBackground')
$('.dbox').removeClass('displayBlock')
// Add a new class to the clicked .cbox & it's child .dbox
$(this).addClass('displayCboxBackground')
$(this).children('.dbox').addClass('displayBlock')
})
The beauty of this? You can have 1000 boxes, it'll still work. No need to add any extra lines of code.
Here's a fiddle showing it in action.
The example code you provided is not consistent with the jsfiddle you created.
In your fiddle, you use the jquery selector $('#quoteClick') but there is no element with that id. There is a #quoteAdvert element however. Change that and you'll see the click in the console.
The classList property returns a token list of the class attribute of the element in question. Luckily for us, it also comes with a few handy methods:
add - adds a class
remove - removes a class
toggle - toggles a class
contains - checks if a class exists
// adds class "foo" to el
el.classList.add("foo");
// removes class "bar" from el
el.classList.remove("bar");
// toggles the class "foo"
el.classList.toggle("foo");
// outputs "true" to console if el contains "foo", "false" if not
console.log( el.classList.contains("foo") );
// add multiple classes to el
el.classList.add( "foo", "bar" );

How do I get a jQuery function to work with specific elements when they have the same class names?

I have sections (divs) with text in it, but when the text is too long I made it so the text "fades" (with css) and displays a "show more" button, which shows the full text for that specific div when clicked. The problem is that it only works for the first div, and I believe it's because they all have the same class and id name. What's the best way to get around that? Here's my code:
HTML:
<div id="fade-container">
<div id="fade-content">
<p>
Long text goes here...
<div class="fade-anchor"><span class="btn-primary round-xl small btn-shadow">Show more</span></div>
</p>
</div>
</div>
Script:
<script>
$('.fade-anchor').click(function(e){
e.preventDefault();
$('#fade-content').css('max-height','none');
$('.fade-anchor').remove();
});
</script>
By the way, info is being fetched from the database in a php while loop.
When the user clicks on .fade-anchor you can use thisto get the element currently selected, you should also use classes instead of ids for multiple elements, like so:
$('.fade-anchor').click(function(e){
e.preventDefault();
$(this).parent('.fade-content').css('max-height','none');
$(this).hide(); // Maybe you should hide instead of removing, in case you want to add a toggle effect later on.
});
You can also check out this jsFiddle with the working version.
Hope it helps.
You can achieve it by e.currentTarget
$('.fade-anchor').click(function(e){
e.preventDefault();
$(e.currentTarget).css('max-height','none');
$('.fade-anchor').remove();});

Showing and hiding text on more than one place on a website by clicking a single link

I want to show and hide content on a webpage by clicking a link 'Click for More text'. While this works fine, my intention is to display more text in two places on the page at the same time.
How can I 'unhide' and hide two different div id's by one click?
<script type="text/javascript">
  function unhide(divID) {
    var item = document.getElementById(divID);
    if (item) {
      item.className=(item.className=='hidden')?'unhidden':'hidden';
    }
}
</script>
and the HTML:
<a href="javascript:unhide(‘content’);”>Click for More text</a>
<div id=“content” class="hidden">
hi
</div>
<div id=“content2” class="hidden">
how can i display this from the same link..?
</div>
Put them in one more div to wrap it and then show just that one
<a href="javascript:unhide(‘content_wrapper’);”>Click for More text</a>
<div id="content_wrapper" class="hidden">
<div id=“content”>
hi
</div>
<div id=“content2”>
how can i display this from the same link..?
</div>
</div>
If you are using jQuery, better idea would be to use classes, check the code below for example
HTML:
<button onclick="unhide('more_info')">
Click for More text
</button>
<div class="more_info hidden">
hi
</div>
<div class="more_info hidden">
how can i display this from the same link..?
</div>
Javascript:
function unhide (arg) {
// toggle class, or remove or add, what ever you need
$('.'+ arg).toggleClass('hidden');
}
EDIT:
To answer question posted by OP in comments.
When it comes to jQuery, most people use only couple of forms of selectors. You can visit this link to find out more about selectors.
For the basics, you are mostly going to be using 2 forms. Personally I use class selector in most cases which is '.selector'
What you can do with it means you use it in form of $('.classSelector') where classSelector can be any class you want to select.
Couple of examples
<div id="test-div-id" class="test-div-class">
<p class="paragraph paragraph-1">This is first</p>
<p class="paragraph paragraph-2">This is second</p>
<p class="paragraph paragraph-3">This is third</p>
</div>
For javascript, you can then use following
$('.test-div-class')
// returns the div by selecting it's class
$('#test-div-id')
// returns the div by selecting it's ID
So if you wanted to check the value of first paragraph you could do
$('.paragraph-1').html();
// returns 'This is first'
You can also select multiple things, let's say you want to hide all paragraphs, you could use .hide() function from jQuery.
$('.paragraph').hide();
// the selector returns collection of all nodes containing class 'paragraph'
// after that we apply function hide.
The last one works on all classes, so you could mix paragraphs and divs and spans and what not. That brings us to next selector, by type
$('p').hide();
// this selector will return every paragraph by type selection
And you can also use what I did in the answer, simple adding of strings
$('.paragraph-1').html();
// returns 'This is first'
var selectorAsAnVariable = 'paragraph-1';
$(selectorAsAnVariable).html();
// returns nothing since it didn't select anything
// this is same as writing $('paragraph-1').html() which would be type selection
// since you don't have type paragraph-1 it fails
$(.selectorAsAnVariable).html();
// this fails on syntax error because unexpected token
$('.selectorAsAnVariable').html();
// returns nothing since it didn't select anything
// this is because you would be trying to select elements which really have that class
$('.'+selectorAsAnVariable).html();
// returns 'This is first'
// this is because this is same as $('.'+'paragraph-1').html()
// which is same as $('.paragraph-1').html() which we know is an class selector
You can also mix them, but I would advise against it because of performance issues, code readability and other reasons, for example you can target div by class and filter paragraph-1 from there. But in most cases it is better to write your code in way that you can avoid that.
For more about the topic, check the link I provided. Also you can use the search to look for other function explanations there.
I hope this clarified things a bit :)

How to temporarily block selectable elements

I am working on a popup menu on my webpage. The menu contains various selectable items, and I would like to only allow selection of certain items after a top-selection has been made. Now I could hide all items lower-down, but that would make the popup look weird. I'd rather show them, but dimmed. My idea was to enclose the follow-up selections in a div, and have that div act as a blocker. Now the question is how to do it - I tried setting the z-index of the selBlocker div higher than the rest, also to give it absolute positioning, but didn't get anywhere yet. I am using a javascript library to handle the selections in general.
<div id="SelPopup" >
<div id="topSelect"></div>
<div id="selBlocker">
<div id="selectable2"></div>
<div id="selectable3"></div>
</div>
</div>
I would append a class to the items you dont want to select, and add the not() selector to your jQuery.
For example:
$("div:not('.selected').....
Instead of
$("div").....
Ofcourse you can add an opacity to the class .selected, to make it a little bit less visible.
You can try below:
Instead of using id for selection blocked element use class="selectBlocked" and for menu div use class="selectMenu"
<div id="SelPopup" >
<div id="topSelect" class="selectMenu"></div>
<div id="selBlocker1" class="selectMenu selectBlocked">
<div id="selectable2"></div>
<div id="selectable3"></div>
</div>
<div id="selBlocker4" class="selectMenu selectBlocked">
<div id="selectable5"></div>
<div id="selectable6"></div>
</div>
</div>
Now right jQuery for handling selection of menu and do nothing if selected menu is with class="selectBlocked"
$('.selectMenu').click(function(){
if($(this).hasClass("selectBlocked"))
return false;
// do your stuff if above condition fails
});
Thank you all for the suggestions, I actually found what I was looking for:
$("#selBlocker").css("pointer-events", "none");
This will nicely disable all interaction, and with
$("#selBlocker").css("pointer-events", "all");
I can restore it. Can add the change in opacity easily alongside it.

Categories

Resources