get content of element after slicing his span - javascript

I have the next element:
<div id = "mydiv">
abc
<span>123</span>
</div>
document.getElementById('mydiv').textContent returns me: abc123
I want to get only the text of mydiv ('abc'). so I wonder if there is an option to use jquery in order to get it? maybe get all the content of an element except for span element..
and then getting his text..
p.s. I know I can wrap abc in span and then get it, but I wonder if there is another option to do it without changing my element..

DEMO JSFIDDLE
Try this ,
console.log($("#mydiv").clone() .children().remove().end().text());

You must select yours DIV by ID, then run through its "childrens" property and check their nodeType (textNodes has 3);
var div = document.getElementById("mydiv");
var result = "";
for(var i = 0; i < div.length; i++){
var node = div[i];
if( node.nodeType === 3 ){
result += node.data;
}
}
console.log(result);

Since you've included jQuery you can do this
var p = $('#mydiv').clone();
p.find('span').remove();
console.log(p.text());
DEMO

Using jQuery:
$(document).ready(function() {
alert($('#mydiv span').text());
});

If you expect to have more html elements inside your div, user regular expression to extract plain text after getting whole html content from div.
var re = /<.+>/;
var str = "abc<span>123</span>";
var newstr = str.replace(re, "");
Should give "abc"

Related

select html element by its full html tag - JS

I am looking for a way to be able to select an HTML element by its tag, like:
document.querySelector("<div id='myDiv'\>hello world</div\>")
//instead of: document.querySelector("#myDiv")
However, this code returns an error. The code should return the HTML element.
Does anybody know a way to achieve this? (vanilla JS preferred)
It seems a bit odd that you wouldn't want to select element via ID. But regardless one way of selecting the element in your example would be to look for its innerHTML.
e.g
var div = document.getElementsByTagName('div');
for (var i=0;i<div.length;i++){
console.log(div[i].innerHTML)
if(div [i].innerHTML == 'hello world'){
var element = div[i].parentElement
console.log(element)
break;
}
}
You could use outerHTML to search for it, however this only works if the element has a parent element.
var els = Array.from(document.querySelector('body *')); //this selects all elements in the body
var el;
for(var i = 0; i < els.length; i++) {
if(els.outerHTML === "<div id='myDiv'\>hello world</div\>") {
el = els[i];
}
}
//Use the el variable for your element

how to select tags that are inside certain other tags

I want to select all the <"a"> tags on a page that are inside all the <"code"> tags on the page so I can count them, and I want to do this using JavaScript.. how can I do this?
I tried using document.getElementsByTagName("code").getElementsByTagName("a"); and document.getElementsByTagName("code").querySelectorAll("a"); but it doesn t seem to work
document.getElementsByTagName("code").getElementsByTagName("a");
VM1278:1 Uncaught TypeError: document.getElementsByTagName(...).getElementsByTagName is not a function
at :1:39
You can use .querySelectorAll(selectors).
const matches = document.querySelectorAll('code a');
console.log(matches);
<code>
<a>Test</a>
<p>Other tag</p>
<a>Example</a>
</code>
You need to loop through the initial element search, since it returns an HTMLCollection of elements:
var elements = document.getElementsByTagName("code");
var all = [];
for(var i = 0; i < elements.length; i++){
var tempElements = elements[i].getElementsByTagName("a");
all = [...tempElements, ...all];
}
Try this instead:
document.querySelectorAll('code a').length
The querySelector and querySelectorAll functions accept CSS-like DOM selectors and return a node or NodeList, respectively.
See:
https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector
https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll
You can use
document.querySelector("code > a");
you can do it like this:
var anchors = document.getElementById("thediv").getElementsByTagName("a");
alert("The Div has " + anchors.length + " links in it");
<div id="thediv">
link 1
link 2
link 3
</div>

Using Javascript, what is the method to get an element, based on the text between the opening and closing tags?

I'm a beginner, and couldn't find the answer after searching.
In my example, I'm looking for an
some text here
I'd want to find this particular element, so I can do stuff with it.
Edit: The only thing I know that's unique about the element for sure, is the text "some text here", that's why I want to find it based on that.
Put id on the element:
<a href="bla" onclick="dah" id='myEl'>some text here</a>
From javascript:
var myEl = document.getElementById('myEl') // gives the element
You can also use psuedo selector :contains, with the jQuery library.
Example 2
$('div:contains("test")').css('background-color', 'red');​
http://jsfiddle.net/9z5du/
Example 2
<script>
$("div:contains('John')").css("text-decoration", "underline");
</script>
If you know that the element is a link, you can first call getElementsByTagName [docs] to narrow down your search:
var elements = document.getElementsByTagName('a');
Then you have to iterate over the elements and test which one contains the next you are looking for:
var element = null;
for(var i = 0, l = elements.length; i < l; i++) {
if(elements[i].innerHTML === 'some text here') {
// found the element
element = elements[i];
break;
}
}
if(element) {
// found the element, lets do something awesome with it
}
There are multiple ways to get the content of an element, using Node#innerText (IE) or Node#textContent (W3C) is another option. You might have to trim the text first before you compare it.
If the HTML is as shown in your post,
if(elements[i].firstChild || elements[i].firstChild.nodeValue)
is even more elegant.
The MDN documentation about the DOM might be helpful.
If you can modify the HTML then adding an ID and using getElementById would be the better option.
Try this
function getit()
{
var elems = document.getElementsByTagName('a');
for(var i=0; i<elems.length; i++)
{
var text = elems[i].childNodes[0] != null ? elems[i].childNodes[0].nodeValue : '';
if(text == "some text here")
doSomethingWith(elems[i]);
}
}

(jquery) change nested same html tag to other bbcode tag

ok here is what i have:
<div id="mydiv">
<font color="green"><font size="3"><font face="helvetica">hello world</font></font></font>
</div>
I know the tags are strange, but that's what produced by the website.
So basically I want to change the font tag to bbcdoe tag, the jquery code I wrote:
$("#mydiv").find("font").text(function(){
var text = $(this).text();
var size = $(this).attr("size");
var color = $(this).attr("color");
var face = $(this).attr("face");;
if(size!=undefined){
return '[size="'+size+'"]'+text+'[/size]';
}
if(color!=undefined){
return '[color="'+color+'"]'+text+'[/color]';
}
if(face!=undefined){
return '[type="'+face+'"]'+text+'[/type]';
}
});
so what I got is only: [color="green"] hello world [/color]. always only the first tag. any idea?
ps: I tried each, replaceWith, html(), all the same result. only the first tag is change.
The reason it doesn't work is because when you call
$("#mydiv").find("font").text("New text")
For each font tag, starting from the first tag, it will replace the text within that tag.
Here is an example to show you what's going on.
Example | Code
$fonts = $("font","#mydiv");
console.log($fonts.text());
$fonts.text(function(){
return "New text";
});
console.log($fonts.text());
Here is an example of how you could do it instead
Example | Code
jQuery.fn.reverse = [].reverse;
var attributes= ["size", "color", "face"];
var text = $.trim($("#mydiv").text());
$("font","#mydiv").reverse().each(function(i, e) {
for (var i = 0; i < attributes.length; ++i){
var attr = $(e).attr(attributes[i]);
if( typeof attr != "undefined")
text = "["+attributes[i]+"="+attr+"]"+text+"[/"+attributes[i]+"]";
}
});
$("#mydiv").text(text);
A room full of sad, wailing kittens wishes that you'd get rid of those <font> tags, but you could probably make it work by explicitly working your way down through the nested tags.
It does what it does now because the outer call to .text() runs for the very first <font> tag, and it obliterates the other tags.
edit — to clarify, when you call
$('#mydiv').find('font')
jQuery will find 3 font tags. The library will therefore call the function you passed into .text() for each of those elements. However, the first call will have the effect of removing the other two <font> elements from the DOM. Even though the library proceeds to call your callback for those elements, there's no effect because they're not on the page anymore.
Here's what could work:
var $fonts = $('#mydiv').find('font');
var text = $fonts.text();
var attrs = {};
$fonts.each(function(_, font) {
var names = ["size", "color", "face"];
for (var i = 0; i < names.length; ++i)
if (font[names[i]]) attrs[names[i]] = font[names[i]];
});
var newText = "";
for (var name in attrs) {
if (attrs.hasOwnProperty(name))
newText += '[' + name + '=' + attrs[name] + ']';
}
newText += text;
for (var name in attrs) {
if (attrs.hasOwnProperty(name))
newText += '[/' + name + ']';
}
$('#mydiv').text(newText);
Note that I'm not really sure why you want to put the BBCode onto the page like that, but it seems to be the intention.
Seems to me your first line should be:
$("#mydiv").find("font").each(function(){

how to remove and <br> using javascript or jQuery?

I have written the following code. But it is removing only not <br>
var docDesc = docDescription.replace(/( )*/g,"");
var docDesc1 = docDescription.replace(/(<br>)*/g,"");
You can achieve removing <br> with CSS alone:
#some_element br {
display: none;
}
If that doesn't fit your needs, and you want to really delete each <br>, it depends, if docDescription is really a string (then one of the above solutions should work, notably Matt Blaine's) or a DOM node. In the latter case, you have to loop through the br elements:
//jquery method:
$('br').remove();
// plain JS:
var brs = common_parent_element.getElementsByTagName('br');
while (brs.length) {
brs[0].parentNode.removeChild(brs[0]);
}
Edit: Why Matt Baline's suggestion? Because he also handles the case, where the <br> appears in an XHTML context with closing slash. However, more complete would be this:
/<br[^>]*>/
Try:
var docDesc = docDescription.replace(/[&]nbsp[;]/gi," "); // removes all occurrences of
docDesc = docDesc.replace(/[<]br[^>]*[>]/gi,""); // removes all <br>
Try this
var text = docDescription.replace(/(?: |<br>)/g,'');
Try "\n"...see if it works.
What about:
var docDesc1 = docDescription.replace(/(<br ?\/?>)*/g,"");
This will depend on the input text but I've just checked that this works:
var result = 'foo <br> bar'.replace(/(<br>)*/g, '');
alert(result);
You can do it like this:
var cell = document.getElementsByTagName('br');
var length = cell.length;
for(var i = 0; i < length; i++) {
cell[0].parentNode.removeChild(cell[0]);
}
It works like a charm. No need for jQuery.
I using simple replace to remove and br tag.
JavaScript
var str = docDescription.replace(/ /g, '').replace(/\<br\s*[\/]?>/gi, '');
jQuery
Remove br with remove() or replaceWith()
$('br').remove();
or
$('br').replaceWith(function() {
return '';
});

Categories

Resources