Just getting started with document.querySelector in JavaScript. Why would
let result = document.querySelector('Lh') return a null. I have tried many permutations with a div as part of the search string but there must be something different about it in a div? Wildcard suggestions...
let result1 = document.querySelector('[class^="Lh(21px)"]')
let result2 = document.querySelector('[class^=".Lh(21px)"]')
let result3 = document.querySelector('[class^="Lh"]')
let result4 = document.querySelector('[class^=".Lh"]')
All return nulls.
<div class="" data-test="quote-mdl" data-yaft-module="tdv2-applet-summary">
<div class="Mb(25px) smartphone_Px(20px)">
<h3 class="Mb(5px)"><span>Summary</span></h3>
<div class="Lh(21px)">Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Sed et magna magna. Praesent in condimentum quam. Phasellus dui ligula,
tincidunt porta fermentum nec. rhoncus id enim. Duis tempor, tellus at
fermentum consectetur, nisl ipsum placerat metus, sed aliquam turpis enim eget erat.
</div>
</div>
</div>
<div class="Lh(21px)">Lorem ipsum dolor ...
The name of your class is Lh(21px) and not Lh, if you want to match any class name that begins with Lh, use the solution provided in this answer:
let result1 = document.querySelector('[class^="Lh"]');
console.log(result1)
<div class="" data-test="quote-mdl" data-yaft-module="tdv2-applet-summary">
<div class="Mb(25px) smartphone_Px(20px)">
<h3 class="Mb(5px)"><span>Summary</span></h3>
<div class="Lh(21px)">Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Sed et magna magna. Praesent in condimentum quam. Phasellus dui ligula,
tincidunt porta fermentum nec. rhoncus id enim. Duis tempor, tellus at
fermentum consectetur, nisl ipsum placerat metus, sed aliquam turpis enim eget erat.
</div>
</div>
</div>
According to MDN:
The Document method querySelector() returns the first Element within the document that matches the specified selector, or group of selectors. If no matches are found, null is returned.
Lh is not a valid selector, because is not a tag but a classname. So you should change your code to this:
const divElement = document.querySelector(".Lh\\(21px\\)")
[EDIT]: Add the backslash if you are using the parenthesis
Related
I learn on how to alert all html code from webpage using this code:
var markup = document.document.innerHTML;
alert(markup);
I want to alert only all <p>
I tried this code
var markup = document.getElementsByTag('p').innerHTML;
alert(markup);`
But it's not working
document.getElementsByTagName("p") returns a HTMLCollection which you can convert to an array using the spread operator. Then you need to get the innerHTML for each element of the array. Finally you can join those innerHTML together to output them:
var pElements = [ ... document.getElementsByTagName("p") ];
var pMarkup = pElements.map( element => element.innerHTML );
alert( pMarkup.join( "\n" ) );
<p>abc<strong>def</strong></p>
<table><tr><td>Don't show this</td></tr></table>
<p>ghi<em>jkl</em></p>
I think you are after HTMLElement.outerHTML
// All p's
const pTags = document.querySelectorAll('p');
const output = [...pTags].map(p => p.outerHTML).join("");
console.log(output);
.red {
color: red;
}
<p class="red">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis at fermentum turpis. Maecenas congue accumsan enim, et dictum turpis malesuada et.
</p>
<p>
Mauris vitae pretium tortor. Aenean nulla ante, scelerisque in erat ac, tincidunt porttitor dolor. Sed blandit sed mi at vulputate.
</p>
<p id="three">
Curabitur lobortis at augue at hendrerit. Mauris id ligula cursus ligula dictum viverra.
</p>
<p>
Sed suscipit varius orci. Duis sit amet fermentum eros. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin commodo turpis in neque aliquam, et laoreet odio consequat.
</p>
<p data-number="5">
Nam dolor neque, lacinia sed viverra et, cursus ac ipsum. Cras gravida quam enim, sit amet tristique urna faucibus non.
</p>
<p>
Phasellus cursus, justo a volutpat pulvinar, ligula metus mollis turpis, in tincidunt ante nisl non nunc.
</p>
I have been working on this for a bit with no success. hope someone has the knowledge i have been looking for.
i have a string that i cant modify from which i need to get all the tags stored in an array.
the string looks like this :
<p><strong>BLA BLA BLA</strong></p>
<p><strong>BLA BLA BLA</p>
<p><em>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse ut mauris vulputate, pellentesque eros sit amet, consequat quam. Nam tempor ipsum ac ligula aliquam, vel dictum elit feugiat. Vivamus vehicula dolor quis ligula malesuada gravida. Curabitur suscipit ante ut sodales sodales. Donec mattis odio a sodales iaculis. Integer urna augue, convallis non euismod a, facilisis vel ex. Nulla sed sodales felis, ac semper odio. Maecenas malesuada justo ac porta faucibus. Aliquam tempor justo ut egestas bibendum.</em></p>
<img alt="lorem ipsum" data-caption="enter caption here" data-entity-type="file" data-entity-uuid="901b744e-a279-4271-9e96-f0836fed3e76" src="https://www.blablabla.com/image.png" />
<p> </p>
<img alt="lorem ipsum" data-caption="enter caption here" data-entity-type="file" data-entity-uuid="901b744e-a279-4271-9e96-f0836fed3e76" src="https://www.blablabla.com/image.png" />
<p> </p>
i was trying with a couple of Regex but they fail to return all the image tags, they return the first one or none at all.
.match('<img.*');
.match('<img\ssrc\s*=\s*"(.+?)\/>');
does anyone know what can i do?
thank you.
You should avoid using regex to parse HTML but since this is a case of img tag which can't be nested, hence in this scope only you can use this regex. Pick the url from group 1
<img.*?\s+src=['"]?(.*)['"]?.*?\/>
Check here,
https://regex101.com/r/qAf16A/3
So I got the following code to create a simple fixed red box:
var red_box = document.createElement('div');
red_box.id = 'caixa_apresentacao_texto';
red_box.style.width = "40%";
red_box.style.overflow = "hidden";
red_box.style.backgroundColor = "white";
red_box.style.color = "black";
red_box.style.border = "5px double red";
/* Centralizing */
red_box.style.position = "fixed";
red_box.style.left = "50%";
red_box.style.marginLeft = "-20%"; //Por que a largura é 40%...
red_box.style.transition = "max-height 1s";
red_box.style.display = "none";
red_box.style.zIndex = "99999999999999";
red_box.style.marginTop = "50px";
red_box.style.maxHeight = "0px";
document.documentElement.insertBefore(red_box,document.body);
So, the idea is that, when I pass some text to this box, it enlarges slowly in order to display it. I get this behaviour with the following code:
var timerHeight;
function expandBox(text){
clearInterval(timerHeight);
/* if the box is empty...*/
if(document.querySelector("#red_box").style.maxHeight == "0px"){
document.querySelector("#red_box").style.display = "inline-block";
red_box.innerHTML = text;
/* Call a function that enlarge the maxHeight property , theorically with the transition letting it more beautiful */
var someText = "text";
timerHeight= setTimeout(enlargeBoxHeight(someText),1);
}
}
function enlargeBoxHeight(anyText){
document.querySelector("#red_box").style.maxHeight ="50px";
}
expandBox("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut sollicitudin euismod metus, at blandit neque maximus ac. Integer fermentum nulla at nibh suscipit, a placerat est pretium. Morbi varius ornare enim, ac pulvinar elit aliquet in. Nullam non diam in nibh consectetur fringilla id nec enim. Mauris lacinia a augue ac consectetur. Etiam tempor et elit a dictum. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam interdum pulvinar pharetra. Aliquam erat volutpat. Aliquam non diam eget turpis tincidunt venenatis at in est. Duis laoreet nibh ultrices erat faucibus hendrerit.")
You can see the fiddle here.
So, I know that 50px is not a good height, but what matters here is that the transition is not working. You may have noticed that the var someText is useless here; but it does have the purpose to express my doubt. I've tried to take it off of the enlargeBoxHeight call. So the last part of the code now is:
...
timerHeight= setTimeout(enlargeBoxHeight,1);
}
}
function enlargeBoxHeight(){
document.querySelector("#red_box").style.maxHeight ="50px";
}
expandBox("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut sollicitudin euismod metus, at blandit neque maximus ac. Integer fermentum nulla at nibh suscipit, a placerat est pretium. Morbi varius ornare enim, ac pulvinar elit aliquet in. Nullam non diam in nibh consectetur fringilla id nec enim. Mauris lacinia a augue ac consectetur. Etiam tempor et elit a dictum. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam interdum pulvinar pharetra. Aliquam erat volutpat. Aliquam non diam eget turpis tincidunt venenatis at in est. Duis laoreet nibh ultrices erat faucibus hendrerit.")
And the surprise: the transition works now. Why? What I am missing here?
When you do:
setTimeout(enlargeBoxHeight,1);
Without the parentheses (), you pass the function enlargeBoxHeight to the timeout, without calling it yet. The timeout will call it after 1ms. Which produced expected behavior + transition.
When you do:
timerHeight= setTimeout(enlargeBoxHeight(someText),1);
You pass the result of the function enlargeBoxHeight to the timeout. () part forces javascript to immediately call the function, and process everything before the timeout. So the transition does not work. After the 1ms, javascript handles the result (with is undefined or irrelevant).
If you want to pass a parameter to a timeout, do:
timerHeight= setTimeout(enlargeBoxHeight.bind(someText),1);
Which should work as expected.
I have several bios that all look like this:
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque tincidunt auctor purus, ut cursus quam fringilla id. Suspendisse a libero id mauris faucibus convallis at ut lacus.
<br><br> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque tincidunt auctor purus, ut cursus quam fringilla id. Suspendisse a libero id mauris faucibus convallis at ut lacus.
<br><br> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque tincidunt auctor purus, ut cursus quam fringilla id. Suspendisse a libero id mauris faucibus convallis at ut lacus.
<br><br> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque tincidunt auctor purus, ut cursus quam fringilla id. Suspendisse a libero id mauris faucibus convallis at ut lacus.
<br><br> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque tincidunt auctor purus, ut cursus quam fringilla id. Suspendisse a libero id mauris faucibus convallis at ut lacus.
<br><br> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque tincidunt auctor purus, ut cursus quam fringilla id. Suspendisse a libero id mauris faucibus convallis at ut lacus.
</p>
Not the prettiest text blocks, but they're auto-generated by the system. I need to iterate through each <p> and take everything after the first set of break tags and wrap that in something like a <div>.
The end result would be:
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque tincidunt auctor purus, ut cursus quam fringilla id. Suspendisse a libero id mauris faucibus convallis at ut lacus.</p>
<div class="theRest">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque tincidunt auctor purus, ut cursus quam fringilla id. Suspendisse a libero id mauris faucibus convallis at ut lacus.
<br><br> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque tincidunt auctor purus, ut cursus quam fringilla id. Suspendisse a libero id mauris faucibus convallis at ut lacus.
<br><br> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque tincidunt auctor purus, ut cursus quam fringilla id. Suspendisse a libero id mauris faucibus convallis at ut lacus.
<br><br> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque tincidunt auctor purus, ut cursus quam fringilla id. Suspendisse a libero id mauris faucibus convallis at ut lacus.
<br><br> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque tincidunt auctor purus, ut cursus quam fringilla id. Suspendisse a libero id mauris faucibus convallis at ut lacus.
</div>
</p>
Try this (inspired of #dave answer):
$("p").each(function(){
// Add a div after the second <br /> (in the current <p>)
$("br:eq(1)", this).after('<div class="theRest"> </ div>');
// Split each "child" in an array
$(this).contents().filter(function(index, elem){
// Keep only children after the <div />
return index > 3;
// Remove and put them into the <div />
}).detach().appendTo($(".theRest", this));
});
Fiddle
Try this:
$('p').each(function() {
$(this).contents(':gt(2)').wrap('<div class="theRest"></div>');
});
But it's not a good enough solution.
For prevent your other p element be wrapped, You should find from any parent element like below:
$('.father').find('p').each(function() {
$(this).contents(':gt(2)').wrap('<div class="theRest"></div>');
});
Try this:
$($("p").contents().get(2)).after('<div class="theRest"></div>');
$("p").contents().filter(function(index, element) {
return index > 3;
}).detach().appendTo(".theRest");
Fiddle
Even though the format returned from server is bad from my standards as it complicates things for the given purpose. However, with some tricks there is still a way to do it.
Explanation: select all nodes, discard the first node because that happens to be the text node, then use jquery wrapAll method to take everything after that node and wrap it up in new div.
Demo: http://jsfiddle.net/qe3bm92e/3/
var txt = $('.txt').contents();
txt.splice(0,1);
txt.wrapAll($("<div>").addClass('red'));
You can replace '.txt' with 'p' but it's not a good practice for very obvious reason.
Suppose we have the following code:
<div id="test" style="width:200px; height: 200px; overflow: hidden;">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus
ipsum diam, cursus ornare eleifend quis, posuere id sapien. Vestibulum
et mattis augue. Nulla facilisi. Sed rhoncus facilisis commodo. Sed mattis
commodo lorem, quis varius est facilisis eget. Integer at nunc metus.
Fusce augue odio, elementum et hendrerit vitae, malesuada at urna.</p>
<p>Consectetur adipiscing elit. Vivamus lorem ipsum dolor sit amet,
ipsum diam, cursus ornare eleifend quis, posuere id sapien. Vestibulum
et mattis augue. Nulla facilisi. Sed rhoncus facilisis commodo. Sed mattis
commodo lorem, quis varius est facilisis eget. Integer at nunc metus.
Fusce augue odio, elementum et hendrerit vitae, malesuada at urna.</p>
<p>Sed rhoncus facilisis commodo. Sed mattis lorem ipsum dolor sit amet,
consectetur adipiscing elit. Vivamus ipsum diam, cursus ornare eleifend
quis, posuere id sapien. Vestibulum et mattis augue. Nulla facilisi.
commodo lorem, quis varius est facilisis eget. Integer at nunc metus.
Fusce augue odio, elementum et hendrerit vitae, malesuada at urna.</p>
</div>
The result would be a clipped text.
Is there some way to get invisible text as a substring?
I tried
$("#test :hidden").text();
and
$('#test').children(":hidden").text()
without success.
I'm trying to show pages of text without scrolling. I have a large amount of text (html formatted) and a fixed size div (the text page). I would like to paginate the text on it, just showing one page of text each time.
There is a good answer on this topic already, it provides the javascript you'd need to do this. Like the respondent there though, I would say find another way to do this if you can.
You could use a mono-spaced font like Lucida Console or Courier New and split the string based on a static number of characters that fit in the content area.