0

When transforming html that contains empty span with a outside text to the jQuery object, I loose the text. I can illustrate this with a simple example:

var test = "<span></span> someText";
var jq = $(test);
console.log(jq.prop('outerHTML'));

This will log only span, without someText (lost).

Can you tell me how could I avoid this? Thank you.

Liam
  • 27,717
  • 28
  • 128
  • 190
gospodin
  • 1,133
  • 4
  • 22
  • 42
  • 1
    `Also outerHTML isn't a prop` yep, it is: https://jsfiddle.net/ydwd6kcm/ – Rory McCrossan Feb 27 '18 at 09:43
  • I stand corrected, I thought props we're for truey falsy values – Liam Feb 27 '18 at 09:43
  • Nope, they work for any property of the Element within the jQuery object – Rory McCrossan Feb 27 '18 at 09:44
  • Code still makes no sense... – Liam Feb 27 '18 at 09:44
  • You are very helpful Liam, thank you – gospodin Feb 27 '18 at 09:45
  • 2
    That part's true :) @gospodin could you please give a little more information about how you ended up with that string. It would be better to avoid this situation if possible. – Rory McCrossan Feb 27 '18 at 09:45
  • 1
    This string is something that I am getting from the external plugins (outside of my app)It is not me who is constructing it and it should not be changed by me. I just want to manipulate it as jQuery object without loosing any data from the initial html. – gospodin Feb 27 '18 at 09:47
  • Possible duplicate of [Creating a jQuery object from a big HTML-string](https://stackoverflow.com/questions/11047670/creating-a-jquery-object-from-a-big-html-string) – Liam Feb 27 '18 at 10:23

1 Answers1

1

It's pretty clunky and unpleasant but you could parse it thus

var test = "<span></span> spanValue";
//turn it into VALID html and parse it.
var jq = $($.parseHTML(test));
console.log(jq.text());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

FYI parseHTML requires jquery 1.8+

Liam
  • 27,717
  • 28
  • 128
  • 190
  • Not a bad idea, but since the desired result is a unmodified test variable, we should not remove the spam from it. So removing the line that removes span and changing the log line to the console.log(jq.prop('innerHTML')); would give me the initial test value in a jquery object. I am wondering if there is any other nicer solution than parsingHtml. Thanks. – gospodin Feb 27 '18 at 10:11
  • What you want this for is unclear. If you just want the text `" spanValue"` then `console.log(test);` would do it? But I'm guessing there is more to it than that? – Liam Feb 27 '18 at 10:20
  • You don't need to append the `

    `

    – Liam Feb 27 '18 at 10:22