How to get value by class name in JavaScript? - javascript

In HTML below, I want to retrieve the value of the all <b> tags using JavaScript or jQuery
<html>
<head>
</head>
<body>
<span id=":zz" class="adl">
<b>2</b>
<b>of </b>
<b>143 </b>
</span>
<body>
</html>
Can I retrieve all <b> tag values using class name in jQuery or JavaScript?

You can place the values in to an array using $.map():
var values = $('b').map(function () {
return $(this).text();
}).get();
console.log(values); // = ["2", "of ", "143 "]
Example fiddle

console.log($('span.adl').find('b').text());

You do not need even need classname to do that.just use:
$('.adl b').each(function(){
alert($(this).html());
})

Related

Javascript innerHTML not changing div contents [duplicate]

This question already has answers here:
What do querySelectorAll and getElementsBy* methods return?
(12 answers)
Closed 4 years ago.
I am trying to change the text displayed by a div from 'hello' to 'hey' on click using innerHTML. I know my function is executed and the innerHTML is changed because I get an alert on click displaying 'hey', but on my webpage and in inspector the 'text' element's contents remain as 'hello'.
What is going on here?
code:
<html>
<head>
<script type="text/javascript">
function changehtml() {
var text = document.getElementsByClassName('text');
text.innerHTML = 'hey';
alert(text.innerHTML)
}
</script>
</head>
<body>
<div class='text' onclick='changehtml()'>
hello
</div>
</body>
</html>
Get elements by class returns an array of elements if you just want to change the one div give it and id and getElementById.
If you want to change multiple divs with that class the second snippet loops through the divs with that class and changes all of their texts.
function changehtml() {
var text = document.getElementById('x');
text.innerHTML = 'hey';
alert(text.innerHTML)
}
<html>
<head>
</head>
<body>
<div id="x" class='text' onclick='changehtml()'>
hello
</div>
</body>
</html>
function changehtml() {
var text = document.getElementsByClassName('text');
for (let i = 0; i < text.length; i++) {
text[i].innerHTML = 'hey';
}
}
<html>
<head>
</head>
<body>
<div class='text' onclick='changehtml()'>
hello
</div>
</body>
</html>
document.getElementsByClassName('text') gives you collection of nodes. So, you;ll have to loop through them to get each node. Or for this example you can use
document.getElementsByClassName('text')[0];
Or
document.querySelector('.text')
This will give you the first node with class name of text.
And make it your habit to check your console for errors, you'll probably be getting one

javascript how to make all strings italic after hyphen?

Good morning to all
I have a question related to my big commerce products title. here I need the first part of the product's title in bold and after the hyphen or dash the second part need in italic. But problem is that the products title comes with one global variable %%GLOBAL_ProductName%% which I cannot make separated with the span tag. so can you suggest me how I can achieve the rest of strings after hyphen show in Italics with the help of javascript?
For example, check this screenshot https://www.screencast.com/t/fKy0FhByzzl
and here is big commerce website http://rp-staging2.mybigcommerce.com/categories
<li class="%%GLOBAL_AlternateClass%%">
<div class="ProductImage" data-product="%%GLOBAL_ProductId%%">
%%GLOBAL_ProductThumb%%
</div>
<div class="OutOfStockMessage InfoMessage" style="%%GLOBAL_ItemSoldOut%%">
%%SNIPPET_SideAddItemSoldOut%%
</div>
<div class="ProductActionAdd" onclick="location.href='%%GLOBAL_ProductLink%%';">
<p>%%GLOBAL_ProductName%%
</p>
<p><em class="p-price">%%GLOBAL_ProductPrice%% USD</em>
</p>
%%GLOBAL_ProductAddText%%
</div>
</li>
%%GLOBAL_ProductName%%
this variable showing products name please check screenshot and website i have provided link
Using some of the cool es6 features (array destructuring and template literals)
$(".pname").each(function () {
[beforeDash, afterDash] = $(this).text().split(" - ");
$(this).html(`${beforeDash} - <i>${afterDash}</i>`);
});
Looks like:
And if you are using jQuery in your website, you can use something like this:
$( window ).on( "load", function(){
var text = $('.text');
var x = text.text().split('-');
text.html(`${x[0]} - <i>${x[1]}<i>`);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="text">
Hello - World
</div>
When ever possible do this kind of split at the server side. Because client side you will manipulate strings after loading the page. So it is not good to do at client side. But anyhow I have written jquery code to fulfill your requirement. I have written in a click event for demo purpose. Please do the logic on onload event.
$("#btn").click(function(){
$(".productName").each(function(){
var title = $(this).text();
var firstSentence = "<b>"+title.substr(0,title.indexOf('-'))+"</b>";
var secondSentence = "<i>"+title.substr(title.indexOf('-')+1)+"</i>";
var finalTitle = firstSentence+ "-" + secondSentence;
$(this).html(finalTitle);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<a class="productName"> Sample1 - Product Name1</a><br>
<a class="productName"> Sample2 - Product Name2</a><br>
<input id="btn" type="button" value="Change Format">
</body>
</html>
Check this if it helps...
https://jsfiddle.net/Lz8p11mc/1/
You need to split your product name with '-' and then add these isolated names in separate spans and then you can style these spans as you want. I have written code for simple test case , you can modify it as per your requirement.
<html>
<script>
var productName = 'ABC-XYZ';
var separatedNames = productName.split('-');
var firtsName = separatedNames[0];
var secondname = separatedNames[1];
window.onload = function() {
//when the document is finished loading, replace everything
//between the <a ...> </a> tags with the value of splitText
document.getElementById("myTag").innerHTML = '<span>'+firtsName+'</span>-<span class="secondnameCls">'+secondname+'</span>';
}
</script>
<body>
<li class="%%GLOBAL_AlternateClass%%">
<p><a id='myTag'></a></p>
</li>
</body>
</html>

using .parent() in jquery

I am trying to loop through a few divs.
Code:
$(".tree div ").each(function () {
var _searchthis = $(this);
var mySearchDiv = _searchthis.parent('div').attr('id');
console.log("this is ID : " + $(this).attr('id'));
console.log("this is parentID : " + mySearchDiv);
});
In case of ID, I am getting the value. But it does not return the .parent('div').attr('id')
I am getting "undefined".
Edited :
When I use .closest() ,instead of .parent(), I get the ID of $(this) only.
.parents('div').first().attr('id') also returns "undefined".
$(".tree li div ").each(function (){
....
}
was a desperate attempt.
HTML Code is more like: http://jsbin.com/yilaw/1/edit
===================================
RESOLVED. I had problem with my HTML structure. Thanks Guys.
Try changing your code to this:
_searchthis.parents("div").eq(0).attr('id');
.parent() parent goes only to the first level while .parents() goes up the stack.
Notice the difference here : http://jsbin.com/labugi/1/edit
html
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<div id="firstLevel">
<span id="secondLevel">
<p id="thirdLevel">
<i id="forthLevel">POC</i>
</p>
<span>
</div>
</body>
</html>
javascript
var result = $('#forthLevel').parent('div').attr('id');
console.log('result of .parent("div"): '+ result);
var result = $('#forthLevel').parents('div').attr('id');
console.log('result of .parents("div"): '+ result);
JQuery says about parent : http://api.jquery.com/parent/
The .parents() and .parent() methods are similar, except that the
latter only travels a single level up the DOM tree.
Use parents instead and get the first element like so : _searchthis.parents('div').eq(0);
Please note : the search query that you are using might be very slow, use classes or ids if possible instead of tagNames.

How to retrieve an input's value without the browser interpreting html special entities?

Is there a way in JavaScript or MooTools to retrieve the actual text in the value from an input element without the browser interpreting any html special entites? Please see the example included below. My desired outcome is:
<div id="output">
<p>Your text is: <b>[<script>alert('scrubbed');</script>]</b></p>
</div>
Note that it works if I type/copy <script>alert('scrubbed');</script> directly into the text input box, but fails if I insert right after loading the page.
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>scrubtest</title>
</head>
<body id="scrubtest" onload="">
<script type="text/javascript" language="JavaScript" src="/js/mootools-core.js"></script>
<input type="text" name="scrubtext" value="<script>alert('scrubbed');</script>" id="scrubtext"/><br />
<input type="button" value="Insert" onclick="insertText();"/><br />
<input type="button" value="Get via MooTools" onclick="alert($('scrubtext').get('value'));"/><br />
<input type="button" value="Get via JavaScript" onclick="alert(document.getElementById('scrubtext').value);"/><br />
<div id="output">
</div>
<script type="text/javascript" charset="utf-8">
function insertText()
{
var stext = $('scrubtext').get('value');
var result = new Element( 'p', {html: "Your text is: <b>["+stext+"]</b>"} );
result.inject($('output'));
}
</script>
</body>
</html>
{html: "Your text is: <b>["+stext+"]</b>"}
That's your problem: you're taking a plain text string and adding it into HTML markup. Naturally any < characters in the text string will become markup, and you give yourself a potential client-side cross-site-scripting vulnerability.
You can HTML-escape, but there's no built-in function to do it in JS, so you have to define it yourself, eg.:
// HTML-encode a string for use in text content or an attribute value delimited by
// double-quotes
//
function HTMLEncode(s) {
return s.replace(/&/g, '&').replace(/</g, '<').replace(/"/g, '"');
}
...
var result = new Element('p', {html: "Your text is: <b>["+HTMLEncode(stext)+"]</b>"});
However, it is generally simpler to use DOM methods to add plain text without the bother of string hacking. I believe Moo would do it like this:
var bold= new Element('b', {text: stext});
var result= new Element('p', {text: 'Your text is: '});
bold.inject(result);
escape & like this: &
<input type="text" name="scrubtext" value="&lt;script&gt;alert('scrubbed');&lt;/script&gt;" id="scrubtext"/>
You can change the & characters into &amp by using
var result = new Element( 'p', {html: "Your text is: <b>["+stext.replace(/&/g,'&amp')+"]</b>"} );
Addition: I would go with bobince on the benefit of using the DOM node properties, instead of injecting arbitrary HTML.
function htmlspecialchars_decode(text)
{
var stub_object = new Element('span',{ 'html':text });
var ret_val = stub_object.get('text');
delete stub_object;
return ret_val;
}

Generate dynamic hyperlink based on querystring

I wanna generate Hyperlink based on query string .Let me explain it more
Topics clicked rite now:(here I want my hyperlinks)....,....
1.Cat1
2.Cat2
3.Cat3
when i click cat1 it generate querystring: ?Cat=Cat1
when I click on cat2 it will generate querystring ?Cat=Cat2
so based on that I want to create hyperlink whose
text is query string(value)
and url is url-(name and value of that query string)lets say for cat1
if currently url is http://www.google.com/?Cat=Cat1&subcat=subcat1
so text should be cat1(and its url should be www.google.com/?subcat=subcat1)
You may want to take a look at the jquery.query plugin. In particular the get function which returns an array of tokens that you can iterate over.
Something like this should get you started:
<html>
<head>
<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.js"></script>
<script type="text/javascript" src="jquery.query.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$.each($.query.get(), function(val, prop) {
$('.menu').append($('<a />').attr('href', $.query.empty().set(val, prop).toString()).text(val));
$('.menu').append($('<br />'));
});
});
</script>
</head>
<body>
<div class="menu">
</div>
</body>
</html>
i would say that probably the way to go for this is the following (syntax isnt correct most likely)
I believe this is some regular string manipulation..
var cat1 = "topic1";
var cat2 = "topic2";
var subcat1 = "subtopic1"; etc
url = "http://google.com/?cat=" + cat1 + "&subcat=" + subcat1
<a href=url/>CAT 1 Link<a>
i hope this helps

Categories