How to get all spans in string variable, with particular class name - javascript

as i am getting tough time to list out all spans, which having class="ansspans", may be one or more span with "ansspans" classes will be there, i need to get all the spans with its content and iterate through it. can you tell me how to do it, Regex, Jquery, any thing ok,
The content will be in string variable (not in DOM), as IE 9 ignoring quotes from attribute, so i cant use getelementbyclass name,and i followed this answer, to get quotes InnerHTml workAround, now its displaying with quotes. so i need get all the class of ansspans, in an array, so that i'll iterate it n get the text content of each span
<span id="sss_ctl00_ctl06_lblanswertext">
assignment
<span class="ansspans">submission </span>
date : 10:07:51 AM
</span>
in this eg, expected output will be 1 span object, so that i can iterate over it
Update : I cant use DOm, as we are in quirks mode, so ie 9 will ignore attribute quotes, which i cant traverse using getelement by class name, . so , i need to match all spans in a string variable. hope everyone understood my problem ;(

(as been said on this site before, sometimes it's ok to parse a limited, known set of xml with regex)
//assumes no <span id="stupid>" class="ansspans">, and no embedded span.ansspans
var data = ' <span id="sss_ctl00_ctl06_lblanswertext"> assignment \n date : 10:07:51 AM \n <span class="ansspans">ONE has a new \n line in it</span><span class="ansspans">TWO</span><span class="ansspans">3 </span><span class="ansspans">4 </span><span class="ansspans">5 </span>';
var myregexp = /<span[^>]+?class="ansspans".*?>([\s\S]*?)<\/span>/g;
var match = myregexp.exec(data);
var result = "spans found:\n";
while (match != null) {
result += "match:"+RegExp.$1 + ',\n';
match = myregexp.exec(data);
}
alert(result);
(edited to capture inner html instead of whole tag)

The following jQuery selector $('span.ansspans') will get all the <span class="anspans"> for the page.
If you need something for a specific element, add a prefix of the appropriate selector, i.e. $('#sss_ctl00_ctl06_lblanswertext span.ansspans')
If this needs to be done in a more dynamic way - look into functions like find(), filter(), etc.

solution using jquery
var tempArray = $("span.ansspans");//this will select all the span elements having class 'ansspans' and return them in an array
var len = tempArray.length;//calculate the length of the array
for(var index = 0;index<len;index++){
var reqString = $(tempArray[index]).html();
}
These string values can be either put inside an array or can be utilised then and there only.
If you want textContent, use .text() instead of .html()

Related

Javascript RegExp unknown repeated matches

It's difficult to describe because I'm not an expert with regular expressions. So I tell you my case.
In HTML want to contribute class attributes into different data-xyz attributes. The problem is to get always all classes per match. For example the following HTML:
<span class="note-123 index-3 green">Hello</span> <span class="index-456 red">World<span>
Until now my regular expression is /<span class="([^\"\s]*)\s*/ and it matches the first class. In this case note-123 and index-456
But if I want to get all classes per element I could use /<span class="([^\"\s]*)\s*([^\"\s]*)\s*([^\"\s]*)\s*/. That works until three classes and the result for the second class return index-456, red and an empty string.
Is there a possibility to always get all classes per match no matter how many classes there are? Similar to a nested loop in Javascript?
I would be pleased to get any help from you guys.
You could get the classes without using a regex making use of querySelectorAll to find the elements that you want and use classList to get the class names.
Then use for example the add or remove methods.
Or use a DOMParser.
Note to close the last span.
let elms = document.querySelectorAll("span");
elms.forEach(e => {
for (let value of e.classList.values()) {
console.log(value);
}
});
<span class="note-123 index-3 green">Hello</span> <span class="index-456 red">World</span>
Use the regex to extract the value of the class attribute and split it at whitespace sequences:
let as_classes
, as_matches
, n_i
, re_classes
, s_test
;
re_classes = new RegExp ( "<span class=\u0022([^\\u0022]*)", "g" );
s_test = '<span class="note-123 index-3 green">Hello</span> <span class="index-456 red">World<span>';
n_i=0;
while ((as_matches = re_classes.exec(s_test)) !== null) {
n_i++;
s_classes = as_matches[1];
as_classes = s_classes.split(/[\s]+/g);
console.log(`match #${n_i}, classes: ${JSON.stringify(as_classes)}.`);
}
Warning
It is in general never a good approach to extract information from html with regexen.

Can I use the % symbol in javascript or it is considered aspecial character?

I need some help.
I need to know if it is possible to use the % symbol in javascript.
I ask this question because I have an html table with the following ID= MRRMFBSY_%_CEC.
When I try to keep the TD of the second TR of this table the results is undefined, so it seems that it doesnt find the Table with this ID and also when it is defined well.
See my code below:
function getColumnsVal(id) {
var header = $("table#" + id + " thead tr:eq(1)");
var header_fields = $("td", header);
// If ID = MRRMFBSY_%_CEC when I try to do an alert of one of my TD,
// example the firstone it returns undefined
alert(header_fields[0]);
}
The question if you think that the problem is the % symbol or not, because when I have the other ID it works perfectly.
Thanks in advance
% is a reserved character, since its an operator (see).
It's not recommended, but you can use it as ID in an HTML element.
See this example:
const element = document.getElementById('MRRMFBSY_%_CEC');
console.log(element); // returns the div element
<div id="MRRMFBSY_%_CEC">
My div with a specific ID
</div>
ISSUE:
There is a problem when using certain special symbols %, ^, +, #, and so on, inside a jquery selector. They should be escaped with a backslash(\) when used because they are also used in forming the queries for the selector.
For instance '#divid' is a valid string in JavaScript but would be confusing to use in jQuery if the string was an actual id of an element. To get this element you have to use
$('#\#divid').
So, in your case to get your target element, $('#MRRMFBSY_\%_CEC') will get the element easily. However, you can either insert the escape character(\) manually or programmatically as done in this post with regular expression. Therefore, using the square brackets or the native getElementById in this answer, is just another way out of this problem.
You can definitely use % symbol in an id attribute (or in any string) as you would use the dash symbol -. However, you cannot use either of both for JavaScript variable names as they are reserved symbols.
SOLUTION:
Though this question has its own intricacies, #misorude has pointed out a solution here. So there lies your answer. use the square brackets [] or document.getElementById like this.
function getColumnsVal(id) {
// var element = $('[id="' + id + '"]'); // this line is equivalent to the next line.
var element = $(document.getElementById(id));
var header = element.find($("thead tr:eq(1)"));
var header_fields = $("td", header);
// If ID = MRRMFBSY_%_CEC when I try to do an alert of one of my TD,
// example the firstone it returns undefined
alert(header_fields[0]);
}

JS. How do I replace text in the html () object within a variable?

Using JS I copied html code into variable.
html_block = $(".first-prj-container").html();
In some places it is necessary to make a replacement for the text. This can be either plain text or class names, IDs. Is it possible to make replacement via strReplace, and then append the result into the page like this:
$("#all-prj-container").append(html_block);
Try this:
let htmlToReplace = $(".first-prj-container").prop('outerHTML')
let updatedHtml = htmlToReplace.replace('hi', 'hello')
$("#all-prj-container").append(updatedHtml);
See more here outerHTML - MDN
you can also use regEx to refine your filter for white spaces, case sensitivity, or filter for certain nested tags:
let updatedHtml= $(".first-prj-container")
.innerHTML.toLowerCase() //make case-insensitive, can also be done with regEx "i"
.replace(/\s/g,'') //remove white spaces
.replace("(hi)(?!(.(?!<h1))*?</h1>)", "hello"); //skip h1 tag content
$(".first-prj-container").innerHTML = updatedHtml;

I am getting empty values for sports-title and third

i am new to js.
can you tell me why I am getting empty values for sports-title and third.
since we have one div with content in it.
sports-title---->{"0":{}}
third---->{}
providing my code below.
findStringInsideDiv() {
/*
var str = document.getElementsByClassName("sports-title").innerHTML;
*/
var sportsTitle = document.getElementsByClassName("sports-title");
var third = sportsTitle[0];
var thirdHTML = third.innerHTML
//str = str.split(" ")[4];
console.log("sports-title---->" + JSON.stringify(sportsTitle));
console.log("third---->" + JSON.stringify(third));
console.log("thirdHTML---->" + JSON.stringify(thirdHTML));
if ( thirdHTML === " basketball football swimming " ) {
console.log("matching basketball---->");
var menu = document.querySelector('.sports');
menu.classList.add('sports-with-basketball');
// how to add this class name directly to the first div after body.
// but we are not rendering that div in accordion
//is it possible
}
else{
console.log("not matching");
}
}
When you call an object in the Document Object Model (DOM) using any of the GetElement selectors, it returns an object that can be considered that HTML element. This object includes much more than just the text included in the HTML element. In order to access the text of that element, you want to use the .textContent property.
In addition, an HTML class can potentially be assigned to several elements and therefore GetElementsByClassName returns an array so you would have to do the following, for example:
console.log("sports-title---->" + JSON.stringify(sportsTitle[0].textContent));
You can find a brief introduction to the DOM on the W3Schools Website. https://www.w3schools.com/js/js_htmldom.asp If you follow along it gives an overview of different aspects of the DOM including elements.
Maybe this would be helpful
As you see sportsTitle[0].textContent returns full heading and 0 is the index thus you get "0" when you stringify (serialize) sportsTitle. Why 0? Because you have one <h1> element . See this fiddle http://jsfiddle.net/cqj6g7f0/3/
I added second h1 and see the console.log and you get two indexes 0 and 1
if you want to get a word from element so get substring use substr() method https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr
One way is to change <h1> class attr to id and do sportsTitle.textContent;
and use substr() on this string
or
2nd way is to remain class attr and do sportsTitle[0].textContent;
and substr() on this string
The 2nd is the better way

How to append string in jQuery without quotes?

Let's say we have a paragraph:
<p>txt0</p>
... and we want to append some text:
$("p").append("_txt1");
$("p").append("_txt2");
$("p").append("_txt3");
The result will be, as expected:
txt0_txt1_txt2_txt3
However if we inspect the result in browser, what it really is:
<p>
"txt0"
"_txt1"
"_txt2"
"_txt3"
</p>
There are 4 different strings that are only rendered as one. The problem is I'm creating a flash object dynamically and appending strings this way will not work because of the quotes. I really need it to be one continuous string like this:
<p>
txt0_txt1_txt2_txt3
</p>
Is there a way to append in such a way? Or to remove all the quotes afterwards?
PS. before you say to make one big string before appending, that won't work because the string is too big and for ex. it works in Chrome but not in Firefox or IExplorer (but that's a different issue).
Use text, otherwise you're appending a new TextNode everytime:
var $p = $('p');
$p.text('txt0');
$p.text($p.text() + '_txt1');
Or with textContent it's less confusing:
var p = $('p')[0];
p.textContent += 'txt0';
p.textContent += '_txt1';
...
You can manipulate the html inside the p-tag this way:
$('p').html($('p').html() + '_text');
My solution is similar to #DonnyDee's
$("p").append("_txt1");
$("p").append("_txt2");
$("p").append("_txt3");
$("p").html($("p").html());
Somehow .html knows how to remove the quotation marks where there are two strings together i.e. "txt0"
"_txt1" etc
afaik .text() is destructive, i.e. will replace html with text which is perhaps not what we want, although I agree for this example it would suffice.
$('p').html(function(index, oldHTML) { return oldHTML + '_text';});
looks like a good solution though. e.g.
$("p").append("_txt1");
$("p").append("_txt2");
$("p").append("_txt3");
$("p").html(function(index, oldHTML) { return oldHTML);

Categories

Resources