jquery / javascript - Simple split() problem - javascript

if ($(".productpage .description").html() != null) {
var textToHide = $('.productpage .description').html().split('<br class="breakHere">')[1];
var visibleText = $('.productpage .description').html().split('<br class="breakHere">')[0];
}
Works great in Firefox, but in IE and Chrome textToHide and visibleText are undefined. Did I miss something? Thanks

View your $('.productpage .description').html(), you may be getting <br />

Using split() against HTML isn't a good idea IMHO - it's too brittle, and is likely to suffer the same problems as using Regexp's against HTML.
Assuming that the elements you're trying to split are all siblings with the <br> element, try this:
var $el = $('.productionpage .description'); // find the element
var $br = $('br.breakHere', $el); // find the BR inside it
var $vis = $br.prevAll(); // contains everything before the break
var $hide = $br.nextAll(); // contains everything after the break
Note that this will give you jQuery objects containing those elements, not the HTML text of them.

Related

How to get text from tags, trimm, and paste to tags again in javascript

I would like to trimm text from html tags, and paste result to these tags again. It's not DOM content, only string.
var string = "<div class='someClass'><b>Some very long text</b></div>"
Wanted result is f.e.:
var string = "<div class='someClass'><b>Some very lon</b></div>"
I found library striptags, but it only gets rid off tags, but I want to keep them.
If you have any solution please let me know :)
UPDATE:
Thanks all of you for advices. There are few things to add from me: 1. I never have information about html tags, because it came from quill text editor, and I need some kind of regex. 2. In my job there is no jQuery, it's kind of 'evil' :P. 3. I'm using react, so any use of 'document' or 'window' is unwanted here :(.
Checkout trim() method of javascript or String.prototype.trim().
Hope it will work for you!
If it is a string and you want to trim some portion of text. you can use the substring/slice function of javascript.
For more refernce you can refer below links
http://www.w3schools.com/jsref/jsref_substring.asp
http://www.w3schools.com/jsref/jsref_slice_string.asp
You could use a hidden tag where you manipulate the string. Something like
<div id="tags-modifier" ></div>
and then jquery like like
var string = "<div class='someClass'><b>Some very long text</b><b>Test2213213213213</b></div>"
$("#tags-modifier").html(string);
var part= 5;
$.each($('#tags-modifier *:not(:has("*"))'), function(){
mytext=$(this).html()
$(this).html(mytext.substring(0, part))
})
string = $("#tags-modifier").html();
This works even if there are multiple siblings
Fiddle here
If the structure is exact like you showed <div class='someClass'><b>Some very long text</b></div>, you could do it with regex to find the text, and in the function change it how you like, shorten(substr)/trim/...:
var longText ="<div class='someClass'><b>Some very long text</b></div>";
const MAX_LENGTH = 13;
// regex expression matches the structure given
var shortText = longText.replace(/(<div[^>]+><b>)([^<]+)(?=<\/b><\/div>)/gi, function(m1,m2,m3){
// m2 matches "<div class='someClass'><b>"
// m3 matches "Some very long"
return m2 + m3.substr(0, MAX_LENGTH).trim();
})
console.info(shortText)
Here some documentation to the replace function https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace
A "cooler" Alternative:
If you pass the HTML Element that should be altered, to this short function checkChildren, all Child-Textnodes will be modified, trim, substr, ...
(it is a bit of an overkill, checking every node, if you know the final structure, but i just wanted to test it):
var elem = document.getElementById("test");
//define the max length of text nodes
const MAX_LENGTH = 13;
checkChildren(elem);
// check all children from parent element an limit the size of textNodes
function checkChildren(parent){
for(var i=0; i<parent.childNodes.length;i++){
var child = parent.childNodes[i];
switch(child.nodeType){
case Node.ELEMENT_NODE:
// recursive call
checkChildren(child);
break;
case Node.TEXT_NODE:
// modify textNode (Shorten and trim)
child.nodeValue = child.nodeValue.substr(0,MAX_LENGTH).trim();
break;
}
}
}
<div id="test" class='someClass'><b>Some very long text</b></div>
You can use $.parseHTML to convert this string into dom tree. Get the <b> node from this dom tree and change the text with the help of substr.

How can I find out whether a HTML-Tagname is Standalone

Is there a way to find out whether a HTML-tagName comes in pair or alone (Standalone-Tag)?
E.g. <div></div>, <em></em>, <p></p>, ... they come in pair, but <br/>, <input>, <area> ... are Standalone.
I need a function which should find out if a HTML-Code snippet is entered correct. Therefore the function has to investigate among others which HTML-Element can be created with Standalone-Tag.
Do you have any idea how can I find out if an HTML element is standalone? Except for example
something like this:
var myArray = [ list of Standalone-Tags ];
if(jQuery.inArray("test", myArray) != -1 ) { ... }
Thanks.
Browsers don't have a built in list of elements which are defined as empty.
You're most reliable bet would be to create one manually by reading the HTML specification.
Alternatively, you could create an element and see what the browser returns when you convert it to HTML.
var element = prompt("What element name? e.g. br");
var container = document.createElement('div');
var content = document.createElement(element);
container.appendChild(content);
var reg = new RegExp("/" + element);
alert(reg.test(container.innerHTML) ? "Not Empty" : "Empty");

jQuery width() not working

I'm trying to get the width of the first div of the specific class "span4" on my Bootstrap site, but the script simply fails to execute the second line where I call width(). Here's what I have:
var span = $('div.span4').first();
spanWidth = span.width();
The strange part of this is that I have similar working code immediately after that works fine when I remove the above two lines and set spanWidth to a constant:
elements = $('a.backlink');
elements.each(function() {
var a = $(this);
if (a.width() > spanWidth) {
var aText = a.text();
var lastIndex = aText.lastIndexOf(' ');
var aTruncated = aText.substring(0, lastIndex);
a.text(aTruncated + '...');
}
});
Any idea what might be causing this? I've tried a lot of different ways to format those two lines differently, such as switching to an each() method, condensing to one line, and using [0] and get(0) instead of first().
Try to set the span's display to inline-block.
#SimonM's comment led me to try replacing my implied global spanWidth with an explicit global window.spanWidth, and now everything works. Thank you!

JQuery: image src variable clean up

I've been teaching myself how to use jquery the past few days, haven't used it much, i'm kinda still stuck in old ways (back 10 yrs ago lol) To get started i downloaded the JQuery Desktop from JQuery Desktop - Nathan Smith, to keep from repetitive use of image src links inevatibly making the file larger than what it needs to be. So while making the reference variables basically started to use the same stuff over again... i tried looking up to see how to compress it or clean it up some but kept running into dead ends for what i am trying to do... if anyone happens to know what i could do that would be awesome.
Code
enter code here
/* SAVES DATA SPACE ALSO CREATES QUICK REFFERENCE/VARIABLE */
var healthVar= 'assets/img/icons/health.png';
var emailVar = 'assets/img/icons/email.png';
var linkVar = 'assets/img/icons/link.png';
var noteVar = 'assets/img/icons/note2.png';
var videoVar = 'assets/img/icons/video1.png';
var xxxVar = 'assets/img/icons/xxx.png';
var socialVar = 'assets/img/icons/social.png';
var webdesktopVar = 'assets/img/icons/webdesktop.png';
var androidVar = 'assets/img/icons/android.png';
var devVar = 'assets/img/icons/development.png';
var secureVar = 'assets/img/icons/secure.png';
var signalVar = 'assets/img/icons/signal.png';
var setVar = 'assets/img/icons/settings.png';
var spamVar = 'assets/img/icons/spam.png';
var feedbackVar = 'assets/img/icons/feedback.png';
$("#health_Pic").attr("src", healthVar);$("#health_PicB").attr("src", healthVar);$("#health_PicC").attr("src", healthVar);
$("#email_Pic").attr("src", emailVar);$("#email_PicB").attr("src", emailVar);$("#email_PicC").attr("src", emailVar);
$("#link_Pic").attr("src", linkVar);$("#link_PicB").attr("src", linkVar);$("#link_PicC").attr("src", linkVar);
$("#note_Pic").attr("src", noteVar);$("#note_PicB").attr("src", noteVar);$("#note_PicC").attr("src", noteVar);
$("#video_Pic").attr("src", videoVar);$("#video_PicB").attr("src", videoVar);$("#video_PicC").attr("src", videoVar);
$("#social_Pic").attr("src",socialVar);$("#social_PicB").attr("src", socialVar);$("#social_PicC").attr("src", socialVar);
$("#webdesktop_Pic").attr("src",webdesktopVar);$("#webdesktop_PicB").attr("src",webdesktopVar);$("#webdesktop_PicC").attr("src",webdesktopVar);
$("#android_Pic").attr("src",androidVar);$("#android_PicB").attr("src",androidVar);$("#android_PicC").attr("src",androidVar);
$("#dev_Pic").attr("src",devVar);$("#dev_PicB").attr("src",devVar);$("#dev_PicC").attr("src",devVar);
$("#secure_Pic").attr("src",secureVar);$("#secure_PicB").attr("src", secureVar);$("#secure_PicC").attr("src", secureVar);
$("#signal_Pic").attr("src", signalVar);$("#signal_PicB").attr("src", signalVar);$("#signal_PicC").attr("src", signalVar);
$("#settings_Pic").attr("src", setVar);$("#settings_PicB").attr("src", setVar);$("#settings_PicC").attr("src", setVar);
$("#spam_Pic").attr("src",spamVar);$("#spam_PicB").attr("src", spamVar);$("#spam_PicC").attr("src", spamVar);
$("#feedback_Pic").attr("src", feedbackVar);$("#feedback_PicB").attr("src", feedbackVar);$("#feedback_PicC").attr("src", feedbackVar)
I have tried to do this:
$("#health_Pic","#health_PicB","#health_PicC").attr("src", healthVar);
With no luck, thanks for any info a head of time
Try:
$("#health_Pic,#health_PicB,#health_PicC").attr("src", healthVar);
The jQuery attr function takes only the first element obtained by the selector.
Get the value of an attribute for the
first element in the set of matched elements.
Use a loop to change multiple images src.
EDIT: After checking the docs and trying it myself, I found that using the .attr as a setter does set the value for all elements. Thanks j08691 for pointing this out.

Is there a getElementsByTagName() like function for javascript string variables?

I can use the getElementsByTagName() function to get a collection of elements from an element in a web page.
I would like to be able to use a similar function on the contents of a javascript string variable instead of the contents of a DOM element.
How do I do this?
EDIT
I can do this by creating an element on the fly.
var myElement = new Element('div');
myElement.innerHTML = "<strong>hello</strong><em>there</em><strong>hot stuff</strong>";
var emCollection = myElement.getElementsByTagName('em');
alert(emCollection.length); // This gives 1
But creating an element on the fly for the convenience of using the getElementsByTagName() function just doesn't seem right and doesn't work with elements in Internet Explorer.
Injecting the string into DOM, as you have shown, is the easiest, most reliable way to do this. If you operate on a string, you will have to take into account all the possible escaping scenarios that would make something that looks like a tag not actually be a tag.
For example, you could have
<button value="<em>"/>
<button value="</em>"/>
in your markup - if you treat it as a string, you may think you have an <em> tag in there, but in actuality, you only have two button tags.
By injecting into DOM via innerHTML you are taking advantage of the browser's built-in HTML parser, which is pretty darn fast. Doing the same via regular expression would be a pain, and browsers don't generally provide DOM like functionality for finding elements within strings.
One other thing you could try would be parsing the string as XML, but I suspect this would be more troublesome and slower than the DOM injection method.
function countTags(html, tagName) {
var matches = html.match(new RegExp("<" + tagName + "[\\s>]", "ig"));
return matches ? matches.length : 0;
}
alert(
countTags(
"<strong>hello</strong><em>there</em><strong>hot stuff</strong>",
"em"
)
); // 1
var domParser = new DOMParser();
var htmlString = "<strong>hello</strong><em>there</em><strong>hot stuff</strong>";
var docElement = domParser.parseFromString(htmlString, "text/html").documentElement;
var emCollection = docElement.getElementsByTagName("em");
for (var i = 0; i < emCollection.length; i++) {
console.log(emCollection[i]);
}
HTML in a string is nothing special. It's just text in a string. It needs to be parsed into a tree for it to be useful. This is why you need to create an element, then call getElementsByTagName on it, as you show in your example.

Categories

Resources