S
S
saalaus2018-07-23 20:36:00
JavaScript
saalaus, 2018-07-23 20:36:00

JavaScript node parser?

In general, I make my text editor on contenteditable, of course there are functions for bold, italic and underlined text on selection, I need to make sure that each element is entered into a separate object, let's say what I enter into the textarea, and what object should I get:

<b>привет, <i>сосед</i></b>, как дела?

{
  "text1":{
    "text": "привет, ",
    "bold": true
  },
  "text2":{
    "text": "сосед",
    "bold": true.
    "italic": true
  },
  "text3":{
    "text":", как дела?"
  }
}

there is such a function, it takes all the child nodes from the parent, takes the text from them, then checks for the presence of tags, and writes the tags, if any
function parseNode(node) {
  let result = [];  
  if (node.hasChildNodes()) {    
    let children = node.childNodes;
    for (var i = 0; i < children.length; ++i) {
      let obj = { 'text': children[i].textContent };
      if (children[i].nodeName === "B") obj.bold = true;
      if (children[i].nodeName === "I") obj.italic = true;
      if (children[i].hasChildNodes() && children[i].childNodes[0].nodeName === "B") { obj.bold = true; }
      if (children[i].hasChildNodes() && children[i].childNodes[0].nodeName === "I") { obj.italic = true; }
      if (children[i].hasChildNodes() && children[i].childNodes[0].nodeName === "U") { obj.undeline = true; }
      result.push(obj);
    }
  }
  return result;
}

the code works correctly, but I had a problem, namely, with the fact that if one text has 1 common tag, and 1 separate one, that is, let's say this:
<b>Привет, <i>сосед</i></b>
then we get such an object:
[Object
  {
    bold:true, 
    text:"Привет, сосед"
}
]

In general, help me fix this, I want to get such an object:
[Object{
  text:"Привет,",
  bold: true
}, Object{
  text:"сосед",
  bold: true,
  italic: true

Sandbox(object in console)

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question