简体   繁体   中英

Grab immediate first character outside of an element

How can I grab the first immediate character before an element in jQuery? This would return d for grabbing the first immediate character before .cursor in this case:

<span class="input">pwd<span class="cursor">&nbsp;</span></span>

Since jQuery ignores regular text nodes, you would need to use some DOM to do what you're doing. I would do something like this:

var sibling = $('.cursor')[0].previousSibling.nodeValue;
console.log(sibling.charAt(sibling.length - 1));

Using jQuery contents()

var text=$('.input').contents().filter(function(){
        return this.nodeType==3 && $(this).next('.cursor').length
    }).text() || ' ';
var lastLetter=text.substr(-1);
var txt = (((($('.cursor')[0] || {}).previousSibling || {}).nodeValue || "").match(/.$/) || [""])[0];

Human-readable: Select ".cursor" and get the first matching element (the actual node, not a jQuery object). Get that node's previous sibling, which should be a text node, and get its node value (the text content). Grab the last character without necessarily knowing the length of the string, and return the matched string. Each step of the way, there is a redundant || {} || {} , || "" || "" or || [""] || [""] to ensure that the following step gets something of the expected type rather than null .

There are a couple things I can think of that might be close to what your looking to do, first please note that it matters where the element you target is and where the previous character would be. First and what would be the easiest would simply be to use regex on the .parent().html() to get the character just before the start of the element.

var content = $(".cursor").parent().html();
var lastChar = content.replace(/.*?(.?)<.*?class="cursor".*?/g, '$1');

Of course you may have to adjust the regex a bit to fit what your doing but that should get you started. If you wanted to get the last character of the previous element from your target (eg pwd ) you could use substr on the .prev().html().

var content = $(".cursor").prev().html();
var lastChar = content.substr( content.length-2, 1 );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM