Zack Zatkin-Gold
Zack Zatkin-Gold

Reputation: 824

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>

Upvotes: 0

Views: 130

Answers (4)

charlietfl
charlietfl

Reputation: 171698

Using jQuery contents()

var text=$('.input').contents().filter(function(){
        return this.nodeType==3 && $(this).next('.cursor').length
    }).text() || ' ';
var lastLetter=text.substr(-1);

Upvotes: 1

user1931103
user1931103

Reputation:

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 );

Upvotes: 0

kennypu
kennypu

Reputation: 6061

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));

Upvotes: 1

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324840

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.

Upvotes: 0

Related Questions